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: 定时器多网关防重复触发 + 前端轮询结果 + 会话历史读修复
caozhenhua0000d36807dd5e24
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 705d92bed6..993138e859 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -18,6 +18,7 @@"test:create-conversation-session": "tsc src/multi-session/state/createConversationSession.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/create-conversation-session --skipLibCheck --noEmitOnError && node --test tests/createConversationSession.test.mjs","test:cron-wake-offset": "tsc src/components/CronPanel/cronWakeOffset.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/cron-wake-offset --skipLibCheck --noEmitOnError && node --test tests/cronWakeOffset.test.mjs","test:cron-project-display": "tsc src/components/CronPanel/cronProjectDisplay.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/cron-project-display --skipLibCheck --noEmitOnError && node --test tests/cronProjectDisplay.test.mjs",+ "test:cron-job-sync": "esbuild src/features/cron/cronJobSync.ts --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/cron-job-sync/cronJobSync.mjs && node --test tests/cronJobSync.test.mjs","test:xiaoyi-cron-target": "tsc src/components/CronPanel/xiaoyiCronTarget.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/xiaoyi-cron-target --skipLibCheck --noEmitOnError && node --test tests/xiaoyiCronTarget.test.mjs","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",diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 219c371d8a..b33069bd86 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -41,8 +41,14 @@ import {normalizeToolCallPayload,normalizeToolResultPayload,} from './features/tool-events/toolEventNormalizer';-import { useWebSocket, mergePersistedGoalCompletionMessages, stampGoalObjectiveMessages } from './hooks';+import {+ useWebSocket,+ mergePersistedGoalCompletionMessages,+ stampGoalObjectiveMessages,+ useCronJobSync,+} from './hooks';import { webRequest } from './services/webClient';+import { getWebTransport } from './utils/env';import { useTeamPanelState } from './features/teamPanelState';import { AgentMode, MediaItem, UserAnswer, ModelEntry, type Session, type UserAnswerStatus } from './types';import {@@ -275,6 +281,8 @@ function AppContent() {});const enterpriseMode = isEnterprise();+ const cronJobPullSyncEnabled = enterpriseMode && getWebTransport() === 'http';+ useCronJobSync(cronJobPullSyncEnabled);const enterpriseBlockedNav = new Set<MainNavKey>(ENTERPRISE_HIDDEN_NAV_ITEMS);const [activeNav, setActiveNav] = useState<MainNavKey>('chat');const [serverConfig, setServerConfig] = useState<Record<string, unknown> | null>(null);diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsxindex cc66b834db..5657805ac8 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx@@ -517,6 +517,7 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSessionasync function handleCreateSubmit(value: CronTaskFormValue) {try {+ const isOnce = cronExprToSchedule(value.cronExpr.trim())?.kind === 'once';await webRequest<{ job: CronJobDTO }>('cron.job.create', {name: value.name.trim(),description: value.description.trim(),@@ -539,6 +540,7 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession...(value.modelName ? { model_name: value.modelName } : {}),mode: value.mode,session_id: sessionId,+ ...(isOnce ? { delete_after_run: true } : {}),});setSuccess(t('cron.success.created'));setDrawer(null);@@ -564,6 +566,7 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSessionasync function handleEditSubmit(jobId: string, value: CronTaskFormValue) {try {const isProactive = jobId === PROACTIVE_AUTO_JOB_ID;+ const isOnce = cronExprToSchedule(value.cronExpr.trim())?.kind === 'once';// proactive 自动维护 job 只允许改 cron_expr 和 timezone;enabled/mode/name/description/// targets/model_name 由 ConfigPanel/cron_sync 管理,不能带,否则会跟 proactive.tick 的// 调度逻辑冲突(沿用 upstream 提交 e64dcf51/59cf6de7 的约束)。@@ -579,6 +582,7 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSessionwake_offset_seconds: normalizeWakeOffsetSeconds(value.wakeOffsetSeconds),...(value.modelName ? { model_name: value.modelName } : {}),mode: value.mode,+ delete_after_run: isOnce,};await webRequest<{ job: CronJobDTO }>('cron.job.update', {id: jobId,diff --git a/jiuwenswarm/channels/web/frontend/src/features/cron/cronJobSync.ts b/jiuwenswarm/channels/web/frontend/src/features/cron/cronJobSync.tsnew file mode 100644index 0000000000..f7a8d9db27--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/cron/cronJobSync.ts@@ -0,0 +1,109 @@+/**+ * Cron job run-state sync (Pull transport).+ *+ * Compares successive `cron.job.list` snapshots and detects new executions via+ * `last_run_at` / `last_session_id`. Used by HTTP mode when server push is unavailable.+ */++export interface CronJobRunFingerprint {+ jobId: string;+ lastRunAt: number | null;+ lastSessionId: string | null;+}++export interface CronJobRunListItem {+ id: string;+ last_run_at?: unknown;+ last_session_id?: unknown;+}++export interface CronJobRunUpdateResult {+ updatedJobIds: string[];+ nextFingerprints: Record<string, CronJobRunFingerprint>;+}++export const CRON_JOB_SYNC_INTERVAL_MS = 30_000;++function normalizeRunAt(raw: unknown): number | null {+ if (typeof raw === 'number' && Number.isFinite(raw)) {+ return raw;+ }+ if (typeof raw === 'string') {+ const trimmed = raw.trim();+ if (!trimmed) {+ return null;+ }+ const parsed = Number(trimmed);+ if (Number.isFinite(parsed)) {+ return parsed;+ }+ }+ return null;+}++function normalizeSessionId(raw: unknown): string | null {+ if (typeof raw !== 'string') {+ return null;+ }+ const trimmed = raw.trim();+ return trimmed || null;+}++export function fingerprintFromCronJob(job: CronJobRunListItem): CronJobRunFingerprint {+ return {+ jobId: job.id,+ lastRunAt: normalizeRunAt(job.last_run_at),+ lastSessionId: normalizeSessionId(job.last_session_id),+ };+}++export function buildCronJobFingerprintMap(+ jobs: CronJobRunListItem[]+): Record<string, CronJobRunFingerprint> {+ const out: Record<string, CronJobRunFingerprint> = {};+ for (const job of jobs) {+ const id = String(job.id || '').trim();+ if (!id) {+ continue;+ }+ out[id] = fingerprintFromCronJob(job);+ }+ return out;+}++function fingerprintChanged(+ previous: CronJobRunFingerprint,+ next: CronJobRunFingerprint+): boolean {+ if (previous.lastRunAt !== next.lastRunAt) {+ return true;+ }+ if (previous.lastSessionId !== next.lastSessionId) {+ return true;+ }+ return false;+}++/**+ * Diff job list against the last sync baseline.+ * Jobs without a prior fingerprint only seed the baseline (no unread).+ */+export function detectCronJobRunUpdates(+ previous: Record<string, CronJobRunFingerprint>,+ jobs: CronJobRunListItem[]+): CronJobRunUpdateResult {+ const nextFingerprints = buildCronJobFingerprintMap(jobs);+ const updatedJobIds: string[] = [];++ for (const [jobId, nextFp] of Object.entries(nextFingerprints)) {+ const prevFp = previous[jobId];+ if (!prevFp) {+ continue;+ }+ if (fingerprintChanged(prevFp, nextFp)) {+ updatedJobIds.push(jobId);+ }+ }++ return { updatedJobIds, nextFingerprints };+}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/index.ts b/jiuwenswarm/channels/web/frontend/src/hooks/index.tsindex 90c5e809ab..4b6437f39b 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/index.ts@@ -5,3 +5,4 @@export { useWebSocket, mergePersistedGoalCompletionMessages, stampGoalObjectiveMessages } from './useWebSocket';export { useSpeechRecognition, useSpeechSynthesis } from './useSpeech';export { useDesktopLocalFilePickerReady } from './useDesktopLocalFilePickerReady';+export { useCronJobSync } from './useCronJobSync';diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useCronJobSync.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useCronJobSync.tsnew file mode 100644index 0000000000..d4c2347a9d--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useCronJobSync.ts@@ -0,0 +1,57 @@+import { useEffect } from 'react';++import { CRON_JOB_SYNC_INTERVAL_MS } from '../features/cron/cronJobSync';+import { useCronStore } from '../stores/cronStore';++/**+ * Pull-based cron run sync for transports without server push (enterprise HTTP).+ * Polls `cron.job.list` on an interval while the document is visible.+ */+export function useCronJobSync(enabled: boolean): void {+ const syncJobRuns = useCronStore((s) => s.syncJobRuns);+ const loadJobs = useCronStore((s) => s.loadJobs);++ useEffect(() => {+ if (!enabled) {+ return;+ }++ let intervalId: number | undefined;+ let cancelled = false;++ const tick = () => {+ if (document.visibilityState !== 'visible') {+ return;+ }+ void syncJobRuns();+ };++ const bootstrap = async () => {+ if (useCronStore.getState().jobs.length === 0) {+ await loadJobs();+ }+ if (cancelled) {+ return;+ }+ tick();+ intervalId = window.setInterval(tick, CRON_JOB_SYNC_INTERVAL_MS);+ };++ const onVisibilityChange = () => {+ if (document.visibilityState === 'visible') {+ tick();+ }+ };++ void bootstrap();+ document.addEventListener('visibilitychange', onVisibilityChange);++ return () => {+ cancelled = true;+ if (intervalId !== undefined) {+ window.clearInterval(intervalId);+ }+ document.removeEventListener('visibilitychange', onVisibilityChange);+ };+ }, [enabled, syncJobRuns, loadJobs]);+}diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.tsindex 912f44becc..53a0b3dc22 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts@@ -79,6 +79,8 @@ const ROUTES: Record<string, RouteRow> = {'locale.get_conf': { verb: 'GET', path: '/locale', kind: 'unary' },'locale.set_conf': { verb: 'PUT', path: '/locale', kind: 'unary' },'cron.job.list': { verb: 'GET', path: '/cron/jobs', kind: 'unary' },+ 'cron.job.create': { verb: 'POST', path: '/cron/jobs', kind: 'unary' },+ 'cron.job.meta': { verb: 'GET', path: '/cron/jobs/meta', kind: 'unary' },'cron.job.get': { verb: 'GET', path: '/cron/jobs/{id}', kind: 'unary' },'cron.job.update': { verb: 'PATCH', path: '/cron/jobs/{id}', kind: 'unary' },'cron.job.delete': { verb: 'DELETE', path: '/cron/jobs/{id}', kind: 'unary' },diff --git a/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/cronStore.tsindex f03365e269..e97e712968 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/cronStore.ts@@ -1,6 +1,11 @@import { create } from 'zustand';-import { webRequest } from '../services/webClient';+import {+ buildCronJobFingerprintMap,+ detectCronJobRunUpdates,+ type CronJobRunFingerprint,+} from '../features/cron/cronJobSync';import { projectRegistryClient } from '../features/workspace/projectRegistryClient';+import { webRequest } from '../services/webClient';import type { Session } from '../types';export interface SidebarCronJob {@@ -15,6 +20,10 @@ export interface SidebarCronJob {targets?: string;created_at: number | string | null;updated_at: number | string | null;+ /** 最近一次执行完成时间(epoch 秒),来自 cron.job.list */+ last_run_at?: number | null;+ /** 最近一次执行会话 ID,来自 cron.job.list */+ last_session_id?: string | null;}/** 判断 cron job 的 targets 是否含 "web"(空串按后端 normalize 默认 web 处理) */@@ -40,6 +49,10 @@ interface CronState {markCronJobUnread: (jobId: string) => void;clearCronJobUnread: (jobId: string) => void;loadJobs: () => Promise<void>;+ /** HTTP Pull transport:静默同步执行状态,发现新 run 时标记未读 */+ syncJobRuns: () => Promise<void>;+ /** cron.job.list 运行态指纹,供 Pull sync diff */+ runSyncFingerprints: Record<string, CronJobRunFingerprint>;reload: () => Promise<void>;toggleCronGroup: (groupId: string) => void;loadCronSessions: (projectId: string, cronId: string) => Promise<void>;@@ -54,9 +67,15 @@ function persistCronUnread(state: Record<string, boolean>) {});}+async function fetchWebCronJobs(): Promise<SidebarCronJob[]> {+ const payload = await webRequest<{ jobs: SidebarCronJob[] }>('cron.job.list');+ return (payload.jobs || []).filter((job) => isWebChannelJob(job.targets));+}+export const useCronStore = create<CronState>((set, get) => ({jobs: [],isLoading: false,+ runSyncFingerprints: {},expandedCronGroups: {},cronSessions: {},cronSessionsLoading: {},@@ -92,12 +111,37 @@ export const useCronStore = create<CronState>((set, get) => ({loadJobs: async () => {set({ isLoading: true });try {- const payload = await webRequest<{ jobs: SidebarCronJob[] }>('cron.job.list');- // 侧边栏是 Web 端工作区,只展示 targets 含 "web" 的定时任务- const webJobs = (payload.jobs || []).filter((j) => isWebChannelJob(j.targets));- set({ jobs: webJobs, isLoading: false });+ const webJobs = await fetchWebCronJobs();+ set({+ jobs: webJobs,+ isLoading: false,+ runSyncFingerprints: buildCronJobFingerprintMap(webJobs),+ });+ } catch {+ set({ jobs: [], isLoading: false, runSyncFingerprints: {} });+ }+ },++ syncJobRuns: async () => {+ try {+ const webJobs = await fetchWebCronJobs();+ const previous = get().runSyncFingerprints;+ const { updatedJobIds, nextFingerprints } = detectCronJobRunUpdates(previous, webJobs);++ set({+ jobs: webJobs,+ runSyncFingerprints: nextFingerprints,+ });++ for (const jobId of updatedJobIds) {+ get().markCronJobUnread(jobId);+ const job = webJobs.find((item) => item.id === jobId);+ if (job) {+ void get().loadCronSessions(job.project_id || 'default', jobId);+ }+ }} catch {- set({ jobs: [], isLoading: false });+ // Pull sync is best-effort; avoid surfacing transient HTTP errors in the sidebar.}},diff --git a/jiuwenswarm/channels/web/frontend/tests/cronJobSync.test.mjs b/jiuwenswarm/channels/web/frontend/tests/cronJobSync.test.mjsnew file mode 100644index 0000000000..eee257a4e5--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/cronJobSync.test.mjs@@ -0,0 +1,47 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ buildCronJobFingerprintMap,+ detectCronJobRunUpdates,+ fingerprintFromCronJob,+} from '../node_modules/.cache/cron-job-sync/cronJobSync.mjs';++test('fingerprintFromCronJob normalizes last_run_at and last_session_id', () => {+ assert.deepEqual(+ fingerprintFromCronJob({+ id: 'job-1',+ last_run_at: '1735689600',+ last_session_id: ' cron_abc_job-1 ',+ }),+ {+ jobId: 'job-1',+ lastRunAt: 1735689600,+ lastSessionId: 'cron_abc_job-1',+ }+ );+});++test('detectCronJobRunUpdates seeds baseline without unread on first sight', () => {+ const jobs = [{ id: 'job-1', last_run_at: 100, last_session_id: 'cron_a' }];+ const result = detectCronJobRunUpdates({}, jobs);+ assert.deepEqual(result.updatedJobIds, []);+ assert.deepEqual(result.nextFingerprints, buildCronJobFingerprintMap(jobs));+});++test('detectCronJobRunUpdates marks last_run_at changes', () => {+ const previous = buildCronJobFingerprintMap([+ { id: 'job-1', last_run_at: 100, last_session_id: 'cron_a' },+ ]);+ const result = detectCronJobRunUpdates(previous, [+ { id: 'job-1', last_run_at: 200, last_session_id: 'cron_b' },+ ]);+ assert.deepEqual(result.updatedJobIds, ['job-1']);+});++test('detectCronJobRunUpdates ignores unchanged snapshots', () => {+ const jobs = [{ id: 'job-1', last_run_at: 100, last_session_id: 'cron_a' }];+ const previous = buildCronJobFingerprintMap(jobs);+ const result = detectCronJobRunUpdates(previous, jobs);+ assert.deepEqual(result.updatedJobIds, []);+});diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex 8fd51feb6f..70c0da6320 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -1775,6 +1775,8 @@ async def _run_with_telemetry(message_handler.set_inbound_pipeline(im_inbound)message_handler.set_outbound_pipeline(im_outbound)+ from jiuwenswarm.gateway.cron.tenant_registry import CronTenantRegistry+cron_registry = CronTenantRegistry.get_instance(agent_client=client,message_handler=message_handler,diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 730284fbd4..f3689e8cd4 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1515,6 +1515,82 @@ class WebHandlersBindParams:a2a_manager: Any = None+_SESSION_LIST_PAGE_SIZE = 200 # Agent ``session.list`` 分页上限,与 handlers/session.py 一致+++async def _fetch_all_sessions_from_agent(+ agent_client: Any,+ *,+ user_id: str | None = None,+ channel_id: str = "web",+) -> list[dict[str, Any]]:+ """Remote 模式下从 AgentServer ``session.list`` 分页拉取全量会话 metadata。"""+ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod++ if agent_client is None:+ return []++ all_sessions: list[dict[str, Any]] = []+ offset = 0+ total: int | None = None+ authenticated_user_id = str(user_id or "").strip() or None++ while True:+ env = e2a_from_agent_fields(+ request_id=f"session-list-{uuid.uuid4().hex[:12]}",+ channel_id=channel_id,+ req_method=ReqMethod.SESSION_LIST,+ params={"limit": _SESSION_LIST_PAGE_SIZE, "offset": offset},+ is_stream=False,+ timestamp=time.time(),+ user_id=authenticated_user_id,+ )+ try:+ response = await agent_client.send_request(env)+ except Exception as exc: # noqa: BLE001+ logger.warning(+ "[session.list] Agent 拉取失败 offset=%s: %s",+ offset,+ exc,+ )+ break++ if not getattr(response, "ok", False):+ payload = response.payload if isinstance(response.payload, dict) else {}+ logger.warning(+ "[session.list] Agent 返回失败 offset=%s: %s",+ offset,+ payload.get("error") or payload,+ )+ break++ payload = response.payload if isinstance(response.payload, dict) else {}+ batch = payload.get("sessions")+ if not isinstance(batch, list):+ break++ for item in batch:+ if isinstance(item, dict):+ all_sessions.append(item)++ raw_total = payload.get("total")+ if isinstance(raw_total, int) and not isinstance(raw_total, bool):+ total = raw_total+ elif total is None:+ total = len(all_sessions)++ if not batch:+ break+ offset += len(batch)+ if total is not None and offset >= total:+ break+ if len(batch) < _SESSION_LIST_PAGE_SIZE:+ break++ return all_sessions++def _attribute_session_project(meta: dict[str, Any],visible_by_id: set[str],@@ -4100,7 +4176,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if limit is not None:limit = max(1, limit)- from jiuwenswarm.server.runtime.session.session_metadata import collect_all_sessions_metadata+ from jiuwenswarm.gateway.routing.session_index import is_remote_storageall_projects = project_store.list_projects(include_hidden=True, cache_bust=True)visible_by_id = {p.project_id for p in all_projects if not p.hidden}@@ -4116,7 +4192,25 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:def _belongs(meta: dict[str, Any]) -> bool:return _attribute_session_project(meta, visible_by_id) == project_id- sessions = collect_all_sessions_metadata()+ if is_remote_storage():+ ac = _resolve(agent_client)+ if ac is None:+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error="AgentServer is unavailable",+ code="SERVICE_UNAVAILABLE",+ )+ return+ sessions = await _fetch_all_sessions_from_agent(+ ac,+ channel_id=channel.channel_id,+ )+ else:+ from jiuwenswarm.server.runtime.session.session_metadata import collect_all_sessions_metadata++ sessions = collect_all_sessions_metadata()# 仅非置顶 cron 会话(cron_id 非空) + 归属匹配 + 可选按 cron_id 过滤# 注意: cron 会话的 channel_id 通常为 "__cron__"(默认模式)或 job.targets(team 模式),# 不固定为 "web",因此不过滤 channel_id,否则 cron 面板会变空。@@ -6751,12 +6845,14 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:await channel.send_response(ws, req_id, ok=False, error="patch must be object", code="BAD_REQUEST")returntry:+ from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple++ g, b, u = extract_routing_triple(params)if hasattr(reg, "web_update_job"):- job = await reg.web_update_job(job_id, patch, sid, aid)+ job = await reg.web_update_job(+ job_id, patch, sid, aid, group_id=g, bot_id=b, user_id=u+ )else:- from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple-- g, b, u = extract_routing_triple(params)job = await cc.update_job(job_id, patch, group_id=g, bot_id=b, user_id=u)await channel.send_response(ws, req_id, ok=True, payload={"job": job})except KeyError:@@ -6788,12 +6884,14 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:)returntry:+ from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple++ g, b, u = extract_routing_triple(params)if hasattr(reg, "web_delete_job"):- deleted = await reg.web_delete_job(job_id, sid, aid)+ deleted = await reg.web_delete_job(+ job_id, sid, aid, group_id=g, bot_id=b, user_id=u+ )else:- from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple-- g, b, u = extract_routing_triple(params)deleted = await cc.delete_job(job_id, group_id=g, bot_id=b, user_id=u)except PermissionError as e:await channel.send_response(ws, req_id, ok=False, error=str(e), code="FORBIDDEN")@@ -6829,12 +6927,20 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:)returntry:+ from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple++ g, b, u = extract_routing_triple(params)if hasattr(reg, "web_toggle_job"):- job = await reg.web_toggle_job(job_id, bool(enabled), sid, aid)+ job = await reg.web_toggle_job(+ job_id,+ bool(enabled),+ sid,+ aid,+ group_id=g,+ bot_id=b,+ user_id=u,+ )else:- from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple-- g, b, u = extract_routing_triple(params)job = await cc.toggle_job(job_id, bool(enabled), group_id=g, bot_id=b, user_id=u)await channel.send_response(ws, req_id, ok=True, payload={"job": job})except KeyError:diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.pyindex 789ee7f233..b9d615c455 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py@@ -209,6 +209,17 @@ _CRON_ROUTES: tuple[WebHttpMappedRoute, ...] = ("cron", "列定时任务",query_keys=_CRON_QUERY,),+ WebHttpMappedRoute(+ "POST", "/cron/jobs", "cron.job.create",+ "cron", "创建定时任务(body 字段与 RPC params 一致)",+ query_keys=_TENANT_QUERY,+ accept_body=True,+ bind_session_param=True,+ ),+ WebHttpMappedRoute(+ "GET", "/cron/jobs/meta", "cron.job.meta",+ "cron", "Cron 元数据(modes/timeout 等)",+ ),WebHttpMappedRoute("GET", "/cron/jobs/{id}", "cron.job.get","cron", "获取单个任务",diff --git a/jiuwenswarm/gateway/cron/db_schedule.py b/jiuwenswarm/gateway/cron/db_schedule.pynew file mode 100644index 0000000000..dfb08199f5--- /dev/null+++ b/jiuwenswarm/gateway/cron/db_schedule.py@@ -0,0 +1,289 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""企业多副本 Cron:以库表 ``next_run_at`` 为调度权威,条件 UPDATE 认领执行权。"""++from __future__ import annotations++import logging+from datetime import datetime, timezone as dt_timezone+from typing import Any+from zoneinfo import ZoneInfo++from jiuwenswarm.gateway.cron.models import CronJob++logger = logging.getLogger(__name__)++_CRON_JOB_TABLE = "cron_job"+++def should_use_db_schedule() -> bool:+ """企业多副本 Cron:实例已绑定且 Gateway 连远程 MySQL/PostgreSQL 时启用库调度。++ 不依赖 ``JIUWENSWARM_EDITION``(部署侧可能只配 ``GATEWAY_EDITION``);+ 与 ``enterprise_cron_enabled()`` + ``GATEWAY_DB_HOST`` 对齐实际连库路径。+ """+ import os++ from jiuwenswarm.gateway.cron.enterprise_gate import enterprise_cron_enabled++ if not enterprise_cron_enabled():+ return False+ return bool(os.getenv("GATEWAY_DB_HOST", "").strip())+++def is_oneshot_job(job: CronJob) -> bool:+ return bool(getattr(job, "delete_after_run", False))+++def compute_next_push_dt(cron_expr: str, timezone: str, *, base: datetime | None = None) -> datetime:+ from jiuwenswarm.gateway.cron.scheduler import _cron_next_push_dt++ tz = ZoneInfo(timezone or "Asia/Shanghai")+ base_dt = base if base is not None else datetime.now(tz=tz)+ if base_dt.tzinfo is None:+ base_dt = base_dt.replace(tzinfo=tz)+ return _cron_next_push_dt(cron_expr, base_dt)+++def compute_next_push_after_fire(job: CronJob, fire_at: datetime) -> datetime | None:+ """由本趟 push 时刻推算下一趟;无下一趟(一次性 cron)返回 None。"""+ tz = ZoneInfo(job.timezone or "Asia/Shanghai")+ if fire_at.tzinfo is None:+ fire_at = fire_at.replace(tzinfo=tz)+ else:+ fire_at = fire_at.astimezone(tz)+ # 过期 fire_at 以当前时间为基准,避免链式补跑积压+ base = max(fire_at, datetime.now(tz))+ try:+ return compute_next_push_dt(+ job.cron_expr,+ job.timezone,+ base=base,+ )+ except Exception as exc:+ if _is_croniter_no_next_date(exc):+ return None+ raise+++def _is_croniter_no_next_date(exc: Exception) -> bool:+ return (+ exc.__class__.__name__ == "CroniterBadDateError"+ or "failed to find next date" in str(exc)+ )+++def next_run_at_to_datetime(job: CronJob) -> datetime | None:+ raw = getattr(job, "next_run_at", None)+ if raw is None:+ return None+ tz = ZoneInfo(job.timezone or "Asia/Shanghai")+ if isinstance(raw, (int, float)):+ return datetime.fromtimestamp(float(raw), tz=tz)+ if isinstance(raw, datetime):+ dt = raw+ return dt if dt.tzinfo is not None else dt.replace(tzinfo=tz)+ if isinstance(raw, str) and raw.strip():+ try:+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=tz)+ return parsed.astimezone(tz)+ except ValueError:+ return None+ return None+++def datetime_to_db_value(dt: datetime) -> datetime:+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=dt_timezone.utc)+ return dt.astimezone(dt_timezone.utc).replace(tzinfo=None)+++def fire_at_from_run_id(run_id: str, job: CronJob) -> datetime | None:+ try:+ push_ts = int(str(run_id).split(":")[-1])+ except (TypeError, ValueError):+ return next_run_at_to_datetime(job)+ tz = ZoneInfo(job.timezone or "Asia/Shanghai")+ return datetime.fromtimestamp(push_ts, tz=tz)+++async def ensure_job_next_run_at(job: CronJob) -> datetime | None:+ """任务缺少 ``next_run_at`` 时计算并写库;返回 push 时刻。"""+ existing = next_run_at_to_datetime(job)+ tz = ZoneInfo(job.timezone or "Asia/Shanghai")+ if existing is not None and existing > datetime.now(tz):+ return existing+ push_dt = compute_next_push_dt(job.cron_expr, job.timezone)+ ok = await _update_next_run_at_only(job.id, push_dt, push_dt)+ if ok:+ job.next_run_at = push_dt.timestamp()+ return push_dt+++async def refresh_job_next_run_at(job: CronJob) -> datetime | None:+ """创建/修改 cron 表达式后重算下一趟并写库。"""+ push_dt = compute_next_push_dt(job.cron_expr, job.timezone)+ ok = await _update_next_run_at_only(job.id, push_dt, push_dt)+ if ok:+ job.next_run_at = push_dt.timestamp()+ return push_dt+++async def claim_periodic_run(job: CronJob, fire_at: datetime) -> bool:+ """周期任务:``next_run_at == fire_at`` 时推进到下一趟,成功即认领本趟。"""+ next_push = compute_next_push_after_fire(job, fire_at)+ if next_push is None:+ return await claim_oneshot_run(job, fire_at)+ return await _claim_update(+ job_id=job.id,+ fire_at=fire_at,+ next_run_at=next_push,+ last_run_at=fire_at,+ )+++async def claim_oneshot_run(job: CronJob, fire_at: datetime) -> bool:+ """一次性任务:``next_run_at == fire_at`` 时标记过期并停用,成功即认领本趟(不删行)。"""+ return await _claim_expire(job_id=job.id, fire_at=fire_at)+++async def _claim_update(+ *,+ job_id: str,+ fire_at: datetime,+ next_run_at: datetime,+ last_run_at: datetime,+) -> bool:+ fire_db = datetime_to_db_value(fire_at)+ next_db = datetime_to_db_value(next_run_at)+ last_db = datetime_to_db_value(last_run_at)+ now_db = datetime_to_db_value(datetime.now(dt_timezone.utc))+ sql = f"""+ UPDATE {_CRON_JOB_TABLE}+ SET next_run_at = :next_run_at,+ last_run_at = :last_run_at,+ updated_at = :updated_at+ WHERE job_id = :job_id+ AND next_run_at = :fire_at+ AND enabled = 1+ AND expired = 0+ """+ params = {+ "job_id": job_id,+ "fire_at": fire_db,+ "next_run_at": next_db,+ "last_run_at": last_db,+ "updated_at": now_db,+ }+ rows = await _execute_claim_sql(sql, params)+ if rows == 1:+ logger.info(+ "[CronDbSchedule] periodic claim ok job_id=%s fire_at=%s next_run_at=%s",+ job_id,+ fire_at.isoformat(),+ next_run_at.isoformat(),+ )+ return True+ logger.warning(+ "[CronDbSchedule] periodic claim miss job_id=%s fire_at=%s rows=%s",+ job_id,+ fire_at.isoformat(),+ rows,+ )+ return False+++async def _claim_expire(*, job_id: str, fire_at: datetime) -> bool:+ fire_db = datetime_to_db_value(fire_at)+ last_db = fire_db+ now_db = datetime_to_db_value(datetime.now(dt_timezone.utc))+ sql = f"""+ UPDATE {_CRON_JOB_TABLE}+ SET expired = 1,+ enabled = 0,+ last_run_at = :last_run_at,+ updated_at = :updated_at+ WHERE job_id = :job_id+ AND next_run_at = :fire_at+ AND enabled = 1+ AND expired = 0+ """+ params = {+ "job_id": job_id,+ "fire_at": fire_db,+ "last_run_at": last_db,+ "updated_at": now_db,+ }+ rows = await _execute_claim_sql(sql, params)+ if rows == 1:+ logger.info(+ "[CronDbSchedule] oneshot claim ok job_id=%s fire_at=%s (marked expired)",+ job_id,+ fire_at.isoformat(),+ )+ return True+ logger.warning(+ "[CronDbSchedule] oneshot claim miss job_id=%s fire_at=%s rows=%s",+ job_id,+ fire_at.isoformat(),+ rows,+ )+ return False+++async def _update_next_run_at_only(+ job_id: str,+ next_run_at: datetime,+ last_run_at: datetime | None,+) -> bool:+ next_db = datetime_to_db_value(next_run_at)+ last_db = (+ datetime_to_db_value(last_run_at)+ if last_run_at is not None+ else None+ )+ now_db = datetime_to_db_value(datetime.now(dt_timezone.utc))+ sets = ["next_run_at = :next_run_at", "updated_at = :updated_at"]+ params: dict[str, Any] = {+ "job_id": job_id,+ "next_run_at": next_db,+ "updated_at": now_db,+ }+ if last_db is not None:+ sets.insert(1, "last_run_at = :last_run_at")+ params["last_run_at"] = last_db+ sql = f"""+ UPDATE {_CRON_JOB_TABLE}+ SET {", ".join(sets)}+ WHERE job_id = :job_id+ """+ rows = await _execute_claim_sql(sql, params)+ return rows == 1+++async def _execute_claim_sql(sql: str, params: dict[str, Any]) -> int:+ from sqlalchemy import text++ from jiuwenswarm.infrastructure.module_importer import import_manager_config_receiver_module++ db_mod = import_manager_config_receiver_module("core.enterprise_config.gateway_db")+ handler = await db_mod.ensure_gateway_db_handler(log_prefix="cron_db_schedule")+ engine = handler.get_engine()+ async with engine.begin() as conn:+ result = await conn.execute(text(sql), params)+ return int(result.rowcount or 0)+++__all__ = (+ "claim_oneshot_run",+ "claim_periodic_run",+ "compute_next_push_after_fire",+ "compute_next_push_dt",+ "ensure_job_next_run_at",+ "fire_at_from_run_id",+ "is_oneshot_job",+ "next_run_at_to_datetime",+ "refresh_job_next_run_at",+ "should_use_db_schedule",+)diff --git a/jiuwenswarm/gateway/cron/db_store.py b/jiuwenswarm/gateway/cron/db_store.pyindex 4bce4fd0ed..3d5b91f144 100644--- a/jiuwenswarm/gateway/cron/db_store.py+++ b/jiuwenswarm/gateway/cron/db_store.py@@ -8,9 +8,10 @@ import asyncioimport jsonimport loggingimport time+from dataclasses import replacefrom datetime import datetime, timezone as dt_timezone+from pathlib import Pathfrom typing import Any-from zoneinfo import ZoneInfofrom jiuwenswarm.gateway.cron.cron_expr import _DEFAULT_WAKE_OFFSET_SECONDSfrom jiuwenswarm.gateway.cron.cron_job_mutations import (@@ -72,16 +73,14 @@ def _dt_to_epoch(value: Any) -> float | None:def _compute_next_run_at(job: CronJob) -> str | None:- try:- from jiuwenswarm.gateway.cron.scheduler import _cron_next_push_dt+ from jiuwenswarm.gateway.cron.db_schedule import (+ compute_next_push_dt,+ datetime_to_db_value,+ )- tz = ZoneInfo(job.timezone or "Asia/Shanghai")- base = datetime.now(tz=tz)- nxt = _cron_next_push_dt(job.cron_expr, base)- if nxt is None:- return None- dt = nxt if nxt.tzinfo is not None else nxt.replace(tzinfo=dt_timezone.utc)- return dt.astimezone(dt_timezone.utc).isoformat()+ try:+ push_dt = compute_next_push_dt(job.cron_expr, job.timezone)+ return datetime_to_db_value(push_dt).isoformat(sep=" ")except Exception:return None@@ -145,6 +144,8 @@ def _row_to_job(row: Any) -> CronJob | None:"user_id": data.get("user_id"),"created_at": _dt_to_epoch(data.get("created_at")),"updated_at": _dt_to_epoch(data.get("updated_at")),+ "next_run_at": _dt_to_epoch(data.get("next_run_at")),+ "last_run_at": _dt_to_epoch(data.get("last_run_at")),}for key in _EXTRA_DATA_KEYS:if key in extra and extra.get(key) is not None:@@ -162,6 +163,11 @@ class GatewayDbCronJobStore:self._lock = asyncio.Lock()self._revision = 0+ @property+ def path(self) -> Path:+ """Compatibility marker for CronTenantRegistry logging."""+ return Path("db://cron_job")+@staticmethodasync def _require_store() -> PersistentStore:from jiuwenswarm.gateway.storage.access import require_persistent_store@@ -173,7 +179,14 @@ class GatewayDbCronJobStore:return {"job_id": job_id}async def get_revision(self) -> int:- return int(self._revision)+ jobs = await self.list_jobs()+ if not jobs:+ return int(self._revision or 0)+ stamp = max(float(j.updated_at or 0) for j in jobs)+ db_rev = int(stamp * 1_000_000)+ if self._revision:+ return max(int(self._revision), db_rev)+ return db_revdef _bump_revision(self) -> None:self._revision = int(time.time() * 1_000_000)@@ -222,6 +235,8 @@ class GatewayDbCronJobStore:)extra = _extra_from_job(job)return {+ "service_id": job.service_id or "default",+ "agent_id": job.agent_id or "default","job_id": job.id,"group_id": job.group_id,"bot_id": job.bot_id,@@ -250,7 +265,13 @@ class GatewayDbCronJobStore:async def create_job(self, **kwargs: Any) -> CronJob:store = await self._require_store()- job = build_new_cron_job(**kwargs)+ tenant_sid = str(kwargs.pop("service_id", None) or "default").strip() or "default"+ tenant_aid = str(kwargs.pop("agent_id", None) or "default").strip() or "default"+ job = replace(+ build_new_cron_job(**kwargs),+ service_id=tenant_sid,+ agent_id=tenant_aid,+ )row_data = self._job_to_row(job)identity = self._job_identity(job_id=job.id)async with self._lock:diff --git a/jiuwenswarm/gateway/cron/enterprise_gate.py b/jiuwenswarm/gateway/cron/enterprise_gate.pyindex 05ea9c6c46..c938a4242d 100644--- a/jiuwenswarm/gateway/cron/enterprise_gate.py+++ b/jiuwenswarm/gateway/cron/enterprise_gate.py@@ -32,11 +32,19 @@ def _resolve_deployment_mode() -> str:def enterprise_cron_enabled(*, deployment_mode: str | None = None) -> bool:- """企业 cron 真正开门:企业版且非 distributed(每网关独立 DB)。"""+ """企业 cron 开门:企业版启用。++ standalone / active-standby:保持历史行为。+ distributed:多副本时需 ``GATEWAY_DB_HOST``,由库表认领避免重复调度。+ """if not is_enterprise():return False- mode = deployment_mode if deployment_mode is not None else _resolve_deployment_mode()- return normalize_deployment_mode(mode) != MODE_DISTRIBUTED+ mode = normalize_deployment_mode(+ deployment_mode if deployment_mode is not None else _resolve_deployment_mode()+ )+ if mode == MODE_DISTRIBUTED:+ return bool(os.getenv("GATEWAY_DB_HOST", "").strip())+ return Truedef coerce_routing_id(value: Any) -> str | None:diff --git a/jiuwenswarm/gateway/cron/job_access.py b/jiuwenswarm/gateway/cron/job_access.pyindex 01b72954f5..17fe68e0de 100644--- a/jiuwenswarm/gateway/cron/job_access.py+++ b/jiuwenswarm/gateway/cron/job_access.py@@ -28,7 +28,20 @@ def create_tenant_cron_store(service_id: str,agent_id: str,) -> Any:- """Return CronJobRepository when PersistentStore is wired; else FileCronJobStore."""+ """Return cron store for tenant scope.++ 企业实例已绑定且连远程库时,走 ``GatewayDbCronJobStore``(与 ``cron_job`` 表结构一致);+ 否则 PersistentStore 可用时用 ``CronJobRepository``;再否则文件 store。+ """+ import os++ from jiuwenswarm.gateway.cron.enterprise_gate import enterprise_cron_enabled++ if enterprise_cron_enabled() and os.getenv("GATEWAY_DB_HOST", "").strip():+ from jiuwenswarm.gateway.cron.db_store import GatewayDbCronJobStore++ return GatewayDbCronJobStore()+store = get_cron_persistent_store()if store is None:from jiuwenswarm.common.utils import resolve_gateway_cron_jobs_pathdiff --git a/jiuwenswarm/gateway/cron/job_repository.py b/jiuwenswarm/gateway/cron/job_repository.pyindex a2dd590a05..00dab81867 100644--- a/jiuwenswarm/gateway/cron/job_repository.py+++ b/jiuwenswarm/gateway/cron/job_repository.py@@ -240,13 +240,14 @@ class CronJobRepository:return deletedasync def get_revision(self) -> int:- if self._revision:- return self._revisionjobs = await self.list_jobs()if not jobs:- return 0+ return int(self._revision or 0)stamp = max(float(j.updated_at or 0) for j in jobs)- return int(stamp * 1_000_000)+ db_rev = int(stamp * 1_000_000)+ if self._revision:+ return max(int(self._revision), db_rev)+ return db_revasync def upsert_from_dict(self, data: dict[str, Any]) -> CronJob:job = CronJob.from_dict(dict(data))diff --git a/jiuwenswarm/gateway/cron/models.py b/jiuwenswarm/gateway/cron/models.pyindex ff78113256..2044bbeded 100644--- a/jiuwenswarm/gateway/cron/models.py+++ b/jiuwenswarm/gateway/cron/models.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field+from datetime import datetime, timezone as dt_timezonefrom enum import Enumfrom typing import Any@@ -252,6 +253,9 @@ class CronJob:session_id: str | None = Nonecreated_at: float | None = Noneupdated_at: float | None = None+ # 企业库调度权威:下一趟 push 时刻(epoch 秒,UTC 语义由 timezone 解释)+ next_run_at: float | None = None+ last_run_at: float | None = None# 记录定时任务是在群聊("group")还是私聊("p2p")中创建的,用于推送时决定是否走 IMOutboundPipelinechat_type: str | None = None# 定时任务执行时使用的 Agent 模式;未指定时默认 agent(plan/fast 已合并)@@ -294,6 +298,8 @@ class CronJob:"targets": self.targets,"created_at": self.created_at,"updated_at": self.updated_at,+ "next_run_at": self.next_run_at,+ "last_run_at": self.last_run_at,"service_id": self.service_id,"agent_id": self.agent_id,}@@ -370,6 +376,23 @@ class CronJob:created_at_f = float(created_at) if isinstance(created_at, (int, float)) else Noneupdated_at_f = float(updated_at) if isinstance(updated_at, (int, float)) else None+ def _epoch_field(key: str) -> float | None:+ val = data.get(key, None)+ if isinstance(val, (int, float)):+ return float(val)+ if isinstance(val, str) and val.strip():+ try:+ parsed = datetime.fromisoformat(val.replace("Z", "+00:00"))+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=dt_timezone.utc)+ return float(parsed.timestamp())+ except ValueError:+ return None+ return None++ next_run_at_f = _epoch_field("next_run_at")+ last_run_at_f = _epoch_field("last_run_at")+if not job_id:raise ValueError("id is required")if not name:@@ -448,6 +471,8 @@ class CronJob:session_id=job_session_id,created_at=created_at_f,updated_at=updated_at_f,+ next_run_at=next_run_at_f,+ last_run_at=last_run_at_f,chat_type=job_chat_type,mode=job_mode,delete_after_run=delete_after_run,@@ -487,3 +512,6 @@ class CronRunState:timezone: str | None = Noneexec_channel_id: str | None = Noneexec_session_id: str | None = None+ # ``cron.job.run_now`` 预分配 run 时使用当前时刻,与库表 ``next_run_at`` 不一致,+ # 不能走条件 UPDATE 认领(否则会静默跳过 wake)。+ manual_trigger: bool = Falsediff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex a80025020c..8267a44b06 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -4,6 +4,7 @@ import asyncioimport heapqimport jsonimport logging+import socketimport timefrom dataclasses import dataclassfrom datetime import datetime, timedelta@@ -32,9 +33,35 @@ from jiuwenswarm.common.work_mode import DEFAULT_WEB_WORK_MODEif TYPE_CHECKING:from jiuwenswarm.gateway.storage.protocols.ephemeral import EphemeralStorefrom jiuwenswarm.server.runtime.session.session_history import append_history_record+from jiuwenswarm.server.runtime.session.session_metadata import _auto_titlelogger = logging.getLogger(__name__)+# run-trace:定位 session.create 与 chat.send 之间断点(phase 见 _log_cron_run_phase)+_CRON_RUN_TRACE_PREFIX = "[Cron][run-trace]"+++def _log_cron_run_phase(+ phase: str,+ *,+ run_id: str = "",+ job_id: str = "",+ exec_session_id: str = "",+ **extra: Any,+) -> None:+ """结构化 Cron 单次执行轨迹日志,便于 grep run_id / exec_session_id。"""+ parts = [f"phase={phase}", f"host={socket.gethostname()}"]+ if job_id:+ parts.append(f"job_id={job_id}")+ if run_id:+ parts.append(f"run_id={run_id}")+ if exec_session_id:+ parts.append(f"exec_session_id={exec_session_id}")+ for key, value in extra.items():+ if value is not None and value != "":+ parts.append(f"{key}={value}")+ logger.info("%s %s", _CRON_RUN_TRACE_PREFIX, " ".join(parts))+def _now_utc_ts() -> float:return time.time()@@ -282,9 +309,64 @@ class CronSchedulerService:self._run_tasks: dict[str, asyncio.Task] = {}self._last_store_revision: int = 0self._store_poll_interval: float = 5.0 # seconds+ # 企业库调度:wake 认领成功的 run_id,push 仅认认领副本处理+ self._claimed_run_ids: set[str] = set()# active-standby 下由 LeaderElection 控制:STANDBY 期间 loop 自旋但不消费事件self._active: bool = True+ def _cancel_run_task(self, run_id: str, task: asyncio.Task, *, reason: str) -> None:+ """取消 in-flight run 并记录来源,便于关联 session.create 后未 chat.send。"""+ if task.done():+ return+ state = self._runs.get(run_id)+ job_id = state.job_id if state is not None else ""+ exec_session_id = (state.exec_session_id or "") if state is not None else ""+ _log_cron_run_phase(+ "run_task_cancel",+ run_id=run_id,+ job_id=job_id,+ exec_session_id=exec_session_id,+ reason=reason,+ task_name=task.get_name(),+ )+ task.cancel()++ def _log_run_task_done(self, run_id: str, task: asyncio.Task) -> None:+ """run agent 协程结束回调:区分正常完成、异常与外部 cancel。"""+ state = self._runs.get(run_id)+ job_id = state.job_id if state is not None else ""+ exec_session_id = (state.exec_session_id or "") if state is not None else ""+ if task.cancelled():+ _log_cron_run_phase(+ "run_task_done_cancelled",+ run_id=run_id,+ job_id=job_id,+ exec_session_id=exec_session_id,+ task_name=task.get_name(),+ )+ return+ exc = task.exception()+ if exc is not None:+ logger.error(+ "%s phase=run_task_done_error job_id=%s run_id=%s exec_session_id=%s "+ "task_name=%s error=%s",+ _CRON_RUN_TRACE_PREFIX,+ job_id,+ run_id,+ exec_session_id,+ task.get_name(),+ exc,+ exc_info=exc,+ )+ return+ _log_cron_run_phase(+ "run_task_done_ok",+ run_id=run_id,+ job_id=job_id,+ exec_session_id=exec_session_id,+ task_name=task.get_name(),+ )+def _run_ephemeral_field(self, run_id: str) -> str:from jiuwenswarm.gateway.storage.state.cron_run_codec import run_field_key@@ -401,13 +483,14 @@ class CronSchedulerService:if active:logger.info("[Cron] scheduler activated (PRIMARY)")else:+ inflight = sum(1 for t in self._run_tasks.values() if not t.done())logger.info("[Cron] scheduler deactivated (STANDBY); cancelling %d in-flight run(s), clearing events",- sum(1 for t in self._run_tasks.values() if not t.done()),+ inflight,)- for t in list(self._run_tasks.values()):+ for rid, t in list(self._run_tasks.items()):if not t.done():- t.cancel()+ self._cancel_run_task(rid, t, reason="scheduler_deactivated_standby")self._run_tasks.clear()self._events.clear()self._runs.clear()@@ -499,9 +582,9 @@ class CronSchedulerService:passself._task = None# best-effort cancel in-flight runs- for t in list(self._run_tasks.values()):+ for rid, t in list(self._run_tasks.items()):if not t.done():- t.cancel()+ self._cancel_run_task(rid, t, reason="scheduler_stop")self._run_tasks.clear()logger.info("[Cron] scheduler stopped")@@ -514,8 +597,15 @@ class CronSchedulerService:continue executing and pushing results despite having no persistent record."""jobs = await self._store.list_jobs()- self._jobs = {j.id: j for j in jobs}- new_job_ids = set(self._jobs.keys())+ all_job_ids = {j.id for j in jobs}+ # 本地内存仅保留运行中(启用且未过期)任务,用于事件队列构建;+ # 过期/已暂停任务仍留在 store 中供前端列表查询。+ running_jobs = [+ j for j in jobs+ if bool(j.enabled) and not bool(getattr(j, "expired", False))+ ]+ self._jobs = {j.id: j for j in running_jobs}+ new_job_ids = all_job_ids# 保留飞行中的 push_update 事件,但仅限于仍存在于 store 中的 job。# 不存在的 job 的 push_update 不应继续推送:store 已无记录意味着@@ -554,7 +644,7 @@ class CronSchedulerService:state.job_id,rid,)- task.cancel()+ self._cancel_run_task(rid, task, reason="ghost_job_removed_from_store")# 向 AgentServer 发送 fire-and-forget 中断请求,让后端真正停止 LLM 处理asyncio.create_task(self._cancel_agent_session(state),@@ -564,9 +654,28 @@ class CronSchedulerService:self._runs.pop(rid, None)now = self._now_fn()+ use_db_schedule = self._use_db_schedule()for job in jobs:try:- push_dt, wake_dt, run_id = self._compute_next_run(job, now_ts=now)+ if use_db_schedule:+ from jiuwenswarm.gateway.cron.db_schedule import (+ ensure_job_next_run_at,+ next_run_at_to_datetime,+ )++ push_dt = next_run_at_to_datetime(job)+ if push_dt is None:+ push_dt = await ensure_job_next_run_at(job)+ if push_dt is None:+ continue+ if getattr(job, "mode", "") == "proactive.tick":+ offset = 0+ else:+ offset = max(0, int(job.wake_offset_seconds or 0))+ wake_dt = push_dt - timedelta(seconds=offset)+ run_id = f"{job.id}:{int(push_dt.timestamp())}"+ else:+ push_dt, wake_dt, run_id = self._compute_next_run(job, now_ts=now)except Exception as exc: # noqa: BLE001if self._is_croniter_no_next_date(exc):# 已过期的 one-shot:标记 expired 并停用,避免 UI 仍显示"运行中/已暂停"。@@ -622,7 +731,11 @@ class CronSchedulerService:# state 并推占位——但此时根本没有执行,推占位会误导用户)。# 仅当内存无该 run 记录时启用此保护(existing is None 即崩溃重启特征)。wake_already_passed = wake_dt.timestamp() <= now- crash_recovery_skip = existing is None and wake_already_passed+ crash_recovery_skip = (+ not use_db_schedule+ and existing is None+ and wake_already_passed+ )if not already_active and not crash_recovery_skip:self._schedule_event(wake_dt, "wake", job.id, run_id)# push 事件:已 active 时仍需排入——_on_push 内部有 pushed_final 兜底,@@ -649,6 +762,7 @@ class CronSchedulerService:job = self._jobs.get(job_id) or await self._store.get_job(job_id)if job is None:raise KeyError("job not found")+ self._jobs[job.id] = jobnow = datetime.now(tz=ZoneInfo(job.timezone))push_dt = nowwake_dt = now@@ -666,6 +780,7 @@ class CronSchedulerService:timezone=job.timezone,exec_channel_id=channel_id,exec_session_id=exec_session_id,+ manual_trigger=True,)await self._assign_run(run_id, state)self._schedule_event(wake_dt, "wake", job.id, run_id)@@ -692,6 +807,14 @@ class CronSchedulerService:project_dir: str,run_id: str,) -> str:+ job_user_id = str(getattr(job, "user_id", None) or "").strip() or None+ _log_cron_run_phase(+ "session_create_begin",+ run_id=run_id,+ job_id=job.id,+ mode=mode,+ request_id=f"cron-session-create-{run_id}",+ )env = e2a_from_agent_fields(request_id=f"cron-session-create-{run_id}",channel_id="__cron__",@@ -705,19 +828,54 @@ class CronSchedulerService:"work_mode": job.work_mode or DEFAULT_WEB_WORK_MODE,"model_name": job.model_name or None,"cron_id": job.id,+ "service_id": str(getattr(job, "service_id", None) or self._service_id),+ "agent_id": str(getattr(job, "agent_id", None) or self._agent_id),+ "group_id": str(getattr(job, "group_id", None) or "").strip(),+ "bot_id": str(getattr(job, "bot_id", None) or "").strip(),+ "user_id": job_user_id or "",+ "title": _auto_title(str(job.description or job.name or "").strip()),},is_stream=False,timestamp=self._now_fn(),+ user_id=job_user_id,+ metadata={+ "cron": {"job_id": job.id, "run_id": run_id},+ "service_id": str(getattr(job, "service_id", None) or self._service_id),+ "agent_id": str(getattr(job, "agent_id", None) or self._agent_id),+ "routing": {+ "bot_id": str(getattr(job, "bot_id", None) or "").strip(),+ "group_id": str(getattr(job, "group_id", None) or "").strip(),+ },+ },)response = await self._agent_client.send_request(env)payload = dict(response.payload or {}) if isinstance(response.payload, dict) else {}if not response.ok:+ _log_cron_run_phase(+ "session_create_failed",+ run_id=run_id,+ job_id=job.id,+ ok=False,+ error=str(payload.get("error") or "cron session.create failed"),+ )raise RuntimeError(str(payload.get("error") or "cron session.create failed"))session_id = str(payload.get("session_id") or payload.get("sessionId") or "").strip()if not session_id:+ _log_cron_run_phase(+ "session_create_empty_session_id",+ run_id=run_id,+ job_id=job.id,+ )raise RuntimeError("cron session.create returned empty session_id")+ _log_cron_run_phase(+ "session_create_ok",+ run_id=run_id,+ job_id=job.id,+ exec_session_id=session_id,+ ok=True,+ )return session_iddef _schedule_event(self, at_dt: datetime, kind: str, job_id: str, run_id: str) -> None:@@ -778,6 +936,76 @@ class CronSchedulerService:or "failed to find next date" in str(exc))+ @staticmethod+ def _use_db_schedule() -> bool:+ from jiuwenswarm.gateway.cron.db_schedule import should_use_db_schedule++ return should_use_db_schedule()++ async def _claim_wake(self, job: CronJob, run_id: str) -> bool:+ if not self._use_db_schedule():+ self._claimed_run_ids.add(run_id)+ return True+ state = self._runs.get(run_id)+ if state is not None and state.manual_trigger:+ self._claimed_run_ids.add(run_id)+ logger.info(+ "[Cron] db schedule claim bypassed (manual run_now) job=%s run_id=%s",+ job.id,+ run_id,+ )+ return True+ from jiuwenswarm.gateway.cron.db_schedule import (+ claim_oneshot_run,+ claim_periodic_run,+ compute_next_push_after_fire,+ fire_at_from_run_id,+ is_oneshot_job,+ )++ fire_at = fire_at_from_run_id(run_id, job)+ if fire_at is None:+ logger.warning(+ "[Cron] db schedule claim skipped: no fire_at job=%s run_id=%s",+ job.id,+ run_id,+ )+ return False+ if is_oneshot_job(job):+ ok = await claim_oneshot_run(job, fire_at)+ if ok:+ self._claimed_run_ids.add(run_id)+ self._jobs.pop(job.id, None)+ else:+ logger.warning(+ "[Cron] db schedule oneshot claim failed job=%s run_id=%s fire_at=%s",+ job.id,+ run_id,+ fire_at.isoformat(),+ )+ return ok+ ok = await claim_periodic_run(job, fire_at)+ if ok:+ self._claimed_run_ids.add(run_id)+ next_push = compute_next_push_after_fire(job, fire_at)+ if next_push is not None:+ job.next_run_at = next_push.timestamp()+ else:+ logger.warning(+ "[Cron] db schedule periodic claim failed job=%s run_id=%s fire_at=%s "+ "db_next_run_at=%s",+ job.id,+ run_id,+ fire_at.isoformat(),+ getattr(job, "next_run_at", None),+ )+ return ok++ def _push_allowed(self, run_id: str) -> bool:+ if not self._use_db_schedule():+ return True+ return run_id in self._claimed_run_ids+async def _loop(self) -> None:while self._running:try:@@ -837,6 +1065,8 @@ class CronSchedulerService:# Handle proactive.tick mode: send WebSocket request to AgentServerif job is not None and job.mode == "proactive.tick" and ev.kind == "wake":+ if not await self._claim_wake(job, ev.run_id):+ returnlogger.info("[Cron] triggering proactive.tick for job=%s run_id=%s", job.id, ev.run_id)try:# Create run state for tracking@@ -886,9 +1116,10 @@ class CronSchedulerService:logger.warning("[Cron] proactive.tick failed job=%s: %s", job.id, state.error)except Exception as exc:logger.warning("[Cron] proactive.tick failed job=%s: %s", job.id, exc, exc_info=True)- # proactive.tick 走专属分支提前 return,跳过下方 643 通用 reschedule。- # 必须显式排下一次 wake,否则只在 reload 时才排,期间漏跑- # (实测:19:56 tick 完,20:00 整点不触发,因为没 reload)。+ # proactive.tick 走专属分支提前 return,跳过下方通用 reschedule。+ if self._use_db_schedule():+ await self.reload()+ returntry:push_dt, wake_dt, next_run_id = self._compute_next_run(job, now_ts=self._now_fn())if push_dt.timestamp() <= self._now_fn():@@ -971,8 +1202,17 @@ class CronSchedulerService:returnif ev.kind == "wake":+ if not await self._claim_wake(job, ev.run_id):+ returnawait self._on_wake(job, ev.run_id)elif ev.kind == "push":+ if not self._push_allowed(ev.run_id):+ logger.debug(+ "[Cron] push skipped: not claim owner job=%s run_id=%s",+ job.id,+ ev.run_id,+ )+ returnawait self._on_push(job, ev.run_id)if job.delete_after_run:# 不删除,改为标记过期(与自然过期的一次性任务行为一致)@@ -995,6 +1235,9 @@ class CronSchedulerService:# proactive.tick 跳过 push 的 reschedule,由 wake 分支统一管调度。if getattr(job, "mode", "") == "proactive.tick":return+ if self._use_db_schedule():+ await self.reload()+ returntry:push_dt, wake_dt, next_run_id = self._compute_next_run(job, now_ts=self._now_fn())if push_dt.timestamp() <= self._now_fn():@@ -1025,6 +1268,13 @@ class CronSchedulerService:else:logger.warning("[Cron] compute next run failed after push job=%s: %s", job.id, exc)elif ev.kind == "push_update":+ if not self._push_allowed(ev.run_id):+ logger.debug(+ "[Cron] push_update skipped: not claim owner job=%s run_id=%s",+ ev.job_id,+ ev.run_id,+ )+ returnawait self._on_push_update(job, ev.run_id)async def _on_wake(self, job: CronJob, run_id: str) -> None:@@ -1066,8 +1316,16 @@ class CronSchedulerService:)returnif run_id in self._run_tasks and not self._run_tasks[run_id].done():+ _log_cron_run_phase(+ "wake_skipped_run_inflight",+ run_id=run_id,+ job_id=job.id,+ task_name=self._run_tasks[run_id].get_name(),+ )return+ _log_cron_run_phase("wake_start_run_agent", run_id=run_id, job_id=job.id)+async def _run_agent() -> None:state.status = "running"state.started_at = self._now_fn()@@ -1076,6 +1334,12 @@ class CronSchedulerService:channel_id = ""exec_session_id = ""envelope = None+ _log_cron_run_phase(+ "run_agent_begin",+ run_id=run_id,+ job_id=job.id,+ task_name=asyncio.current_task().get_name() if asyncio.current_task() else "",+ )try:mode = str(job.mode or CRON_JOB_DEFAULT_MODE).strip() or CRON_JOB_DEFAULT_MODEif state.exec_channel_id and state.exec_session_id:@@ -1095,6 +1359,12 @@ class CronSchedulerService:)exec_project_dir = ""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,@@ -1103,6 +1373,12 @@ class CronSchedulerService:)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,@@ -1139,12 +1415,27 @@ class CronSchedulerService:params=params,is_stream=is_team_cron_mode(mode),timestamp=self._now_fn(),+ user_id=str(getattr(job, "user_id", None) or "").strip() or None,metadata={"cron": {"job_id": job.id, "run_id": run_id},"service_id": self._service_id,"agent_id": self._agent_id,+ "routing": {+ "bot_id": str(getattr(job, "bot_id", None) or "").strip(),+ "group_id": str(getattr(job, "group_id", None) or "").strip(),+ },},)+ _log_cron_run_phase(+ "run_agent_chat_envelope_ready",+ run_id=run_id,+ job_id=job.id,+ exec_session_id=exec_session_id,+ request_id=f"cron-{run_id}",+ channel_id=channel_id,+ is_team=is_team_cron_mode(mode),+ query_len=len(str(job.description or "")),+ )if is_team_cron_mode(mode):timeout_seconds = resolve_cron_job_timeout_seconds(job)text, ok = await self._run_team_stream_job(@@ -1156,11 +1447,26 @@ class CronSchedulerService:else:envelope.is_stream = Falsetimeout_seconds = resolve_cron_job_timeout_seconds(job)+ _log_cron_run_phase(+ "run_agent_before_chat_send",+ run_id=run_id,+ job_id=job.id,+ exec_session_id=exec_session_id,+ timeout_seconds=timeout_seconds,+ )text, ok = await self._run_unary_cron_job(envelope=envelope,timeout_seconds=timeout_seconds,state=state,)+ _log_cron_run_phase(+ "run_agent_after_chat_send",+ run_id=run_id,+ job_id=job.id,+ exec_session_id=exec_session_id,+ ok=ok,+ result_text_len=len(text or ""),+ )await self._mark_last_session_ready(job, exec_session_id)logger.info("[Cron] run finished: job_id=%s exec_session_id=%s "@@ -1172,6 +1478,14 @@ class CronSchedulerService:except asyncio.CancelledError:state.status = "failed"state.error = "cancelled"+ _log_cron_run_phase(+ "run_agent_cancelled",+ run_id=run_id,+ job_id=job.id,+ exec_session_id=exec_session_id or state.exec_session_id or "",+ envelope_built=envelope is not None,+ had_result_text=bool(state.result_text),+ )# Ghost task: cancelled by reload because job no longer in store.# Do NOT schedule push_update — the user has removed this job and# should not see any result from it. Raising CancelledError here@@ -1181,6 +1495,20 @@ class CronSchedulerService:except Exception as exc: # noqa: BLE001state.status = "failed"state.error = str(exc)+ _log_cron_run_phase(+ "run_agent_exception",+ run_id=run_id,+ job_id=job.id,+ exec_session_id=exec_session_id or state.exec_session_id or "",+ envelope_built=envelope is not None,+ error=str(exc),+ )+ logger.exception(+ "[Cron] run_agent failed job_id=%s run_id=%s exec_session_id=%s",+ job.id,+ run_id,+ exec_session_id or state.exec_session_id or "",+ )finally:state.finished_at = self._now_fn()is_cancelled_ghost = state.error == "cancelled"@@ -1191,10 +1519,32 @@ class CronSchedulerService:if not state.result_text and state.error and not is_cancelled_ghost:state.result_text = f"[cron] 任务执行失败: {state.error}"if state.result_text and not ok and not is_cancelled_ghost:+ query = ""+ if envelope is not None and isinstance(envelope.params, dict):+ query = str(+ envelope.params.get("query")+ or envelope.params.get("content")+ or ""+ ).strip()+ if not query:+ query = str(job.description or job.name or "").strip()+ req_id = getattr(envelope, "request_id", "") if envelope else ""+ ch = job.targets or channel_id+ started = state.started_at or self._now_fn()+ if query:+ append_history_record(+ session_id=exec_session_id,+ request_id=req_id,+ channel_id=ch,+ role="user",+ content=query,+ timestamp=started,+ mode=mode,+ )append_history_record(session_id=exec_session_id,- request_id=getattr(envelope, "request_id", ""),- channel_id=job.targets or channel_id,+ request_id=req_id,+ channel_id=ch,role="assistant",event_type="chat.final",content=state.result_text,@@ -1217,8 +1567,15 @@ class CronSchedulerService:"push_update", job.id, run_id,)- task = asyncio.create_task(_run_agent(), name=f"cron-run-{job.id}")+ task = asyncio.create_task(_run_agent(), name=f"cron-run-{job.id}-{run_id}")self._run_tasks[run_id] = task+ task.add_done_callback(lambda t: self._log_run_task_done(run_id, t))+ _log_cron_run_phase(+ "run_agent_task_scheduled",+ run_id=run_id,+ job_id=job.id,+ task_name=task.get_name(),+ )async def _mark_last_session_ready(self, job: CronJob, exec_session_id: str) -> None:"""Record the execution session after the agent request has accepted it."""@@ -1293,6 +1650,16 @@ class CronSchedulerService:timeout_seconds: float,state: CronRunState,) -> tuple[str, bool]:+ rid = str(getattr(envelope, "request_id", "") or "")+ sid = str(getattr(envelope, "session_id", "") or "")+ _log_cron_run_phase(+ "chat_send_http_begin",+ run_id=state.run_id,+ job_id=state.job_id,+ exec_session_id=sid,+ request_id=rid,+ timeout_seconds=timeout_seconds,+ )try:resp = await asyncio.wait_for(self._agent_client.send_request(envelope),@@ -1300,6 +1667,15 @@ class CronSchedulerService:)text = _extract_text_from_agent_payload(resp.payload)ok = bool(resp.ok)+ _log_cron_run_phase(+ "chat_send_http_done",+ run_id=state.run_id,+ job_id=state.job_id,+ exec_session_id=sid,+ request_id=rid,+ ok=ok,+ result_text_len=len(text or ""),+ )# 成功但 result_text 为空:响应格式与 _extract_text_from_agent_payload# 的识别字段不匹配(如 E2A result 非 dict、或字段名不在 error/content/# heartbeat/text 之内)。若放任空字符串进入 state.result_text,会触发@@ -1320,6 +1696,14 @@ class CronSchedulerService:return text, okexcept asyncio.TimeoutError:timeout_min = max(1, int(timeout_seconds // 60))+ _log_cron_run_phase(+ "chat_send_http_timeout",+ run_id=state.run_id,+ job_id=state.job_id,+ exec_session_id=sid,+ request_id=rid,+ timeout_seconds=timeout_seconds,+ )logger.warning("[Cron] unary request timed out after %ss request_id=%s",timeout_seconds,diff --git a/jiuwenswarm/gateway/cron/tenant_registry.py b/jiuwenswarm/gateway/cron/tenant_registry.pyindex ba157a4556..d892276045 100644--- a/jiuwenswarm/gateway/cron/tenant_registry.py+++ b/jiuwenswarm/gateway/cron/tenant_registry.py@@ -250,19 +250,43 @@ class CronTenantRegistry:return dataasync def web_update_job(- self, job_id: str, patch: dict[str, Any], service_id: str, agent_id: str+ self,+ job_id: str,+ patch: dict[str, Any],+ service_id: str,+ agent_id: str,+ *,+ group_id: str | None = None,+ bot_id: str | None = None,+ user_id: str | None = None,) -> dict[str, Any]:data = await (await self.get_controller(service_id, agent_id)).update_job(- job_id, patch+ job_id,+ patch,+ group_id=group_id,+ bot_id=bot_id,+ user_id=user_id,)await self._mirror_after_mutation(service_id=service_id, agent_id=agent_id, job=data)return data- async def web_delete_job(self, job_id: str, service_id: str, agent_id: str) -> bool:+ async def web_delete_job(+ self,+ job_id: str,+ service_id: str,+ agent_id: str,+ *,+ group_id: str | None = None,+ bot_id: str | None = None,+ user_id: str | None = None,+ ) -> bool:deleted = await (await self.get_controller(service_id, agent_id)).delete_job(- job_id+ job_id,+ group_id=group_id,+ bot_id=bot_id,+ user_id=user_id,)if deleted:await self._mirror_after_mutation(@@ -271,10 +295,22 @@ class CronTenantRegistry:return deletedasync def web_toggle_job(- self, job_id: str, enabled: bool, service_id: str, agent_id: str+ self,+ job_id: str,+ enabled: bool,+ service_id: str,+ agent_id: str,+ *,+ group_id: str | None = None,+ bot_id: str | None = None,+ user_id: str | None = None,) -> dict[str, Any]:data = await (await self.get_controller(service_id, agent_id)).toggle_job(- job_id, enabled+ job_id,+ enabled,+ group_id=group_id,+ bot_id=bot_id,+ user_id=user_id,)await self._mirror_after_mutation(service_id=service_id, agent_id=agent_id, job=datadiff --git a/jiuwenswarm/gateway/storage/state/cron_run_codec.py b/jiuwenswarm/gateway/storage/state/cron_run_codec.pyindex 3c1f9099f9..de0d5c70d5 100644--- a/jiuwenswarm/gateway/storage/state/cron_run_codec.py+++ b/jiuwenswarm/gateway/storage/state/cron_run_codec.py@@ -45,6 +45,7 @@ def cron_run_from_bytes(raw: bytes) -> CronRunState:timezone=data.get("timezone"),exec_channel_id=data.get("exec_channel_id"),exec_session_id=data.get("exec_session_id"),+ manual_trigger=bool(data.get("manual_trigger", False)),)diff --git a/jiuwenswarm/server/handlers/session.py b/jiuwenswarm/server/handlers/session.pyindex 746e1feb3d..e89482bebe 100644--- a/jiuwenswarm/server/handlers/session.py+++ b/jiuwenswarm/server/handlers/session.py@@ -125,17 +125,19 @@ async def _resolve_rewind_agent(return (deep_agent, react_agent)-def get_conversation_history(session_id: str, page_idx: int) -> dict[str, Any] | None:+def get_conversation_history(+ session_id: str, page_idx: int, sessions_root: str | None = None,+) -> dict[str, Any] | None:# 按照 session_id 和分页消息获取历史记录if not isinstance(session_id, str) or not session_id.strip():return Noneif not isinstance(page_idx, int) or page_idx <= 0:return Nonenormalized_session_id = session_id.strip()- if not history_exists(normalized_session_id):+ if not history_exists(normalized_session_id, sessions_root=sessions_root):return Nonetry:- raw = load_history_records(normalized_session_id)+ raw = load_history_records(normalized_session_id, sessions_root=sessions_root)except Exception:return Noneif not isinstance(raw, list):@@ -800,7 +802,10 @@ async def handle_history_get(ctx: RequestContext) -> None:session_id = params.get("session_id")# 归一化数字型参数page_idx = _coerce_int(params.get("page_idx"), 0)- data = get_conversation_history(session_id=session_id, page_idx=page_idx)+ sessions_root = str(_sessions_dir_for_request(request))+ data = get_conversation_history(+ session_id=session_id, page_idx=page_idx, sessions_root=sessions_root,+ )if data is None:resp = AgentResponse(request_id=request.request_id,@@ -825,7 +830,10 @@ async def handle_history_get_stream(ctx: RequestContext) -> None:session_id = params.get("session_id")# 归一化数字型参数page_idx = _coerce_int(params.get("page_idx"), 0)- data = get_conversation_history(session_id=session_id, page_idx=page_idx)+ sessions_root = str(_sessions_dir_for_request(request))+ data = get_conversation_history(+ session_id=session_id, page_idx=page_idx, sessions_root=sessions_root,+ )if data is None:err_chunk = AgentResponseChunk(request_id=request.request_id,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex d8836f6ea8..4a469ac1e6 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -2646,7 +2646,7 @@ class JiuWenSwarmDeepAdapter:config["request"] = requestcreate_started_at = time.monotonic()await adapter.create_instance(- config,+ config if config else None,mode=self._session_instance_mode,sub_mode=self._session_instance_sub_mode,config_base=self._config_base_cache,@@ -5442,6 +5442,18 @@ class JiuWenSwarmDeepAdapter:if not self._model_cache:self._build_model_cache_legacy(config)+ if not self._model_cache:+ # config.yaml 占位条目无效时,回退到进程环境变量(API_BASE/API_KEY/MODEL_NAME)+ env_fallback_counter: dict[str, int] = {}+ for entry in get_default_models({"models": {}}):+ try:+ self._register_model_cache_entry(entry, env_fallback_counter)+ except Exception as exc:+ logger.warning(+ "[JiuWenSwarmDeepAdapter] 跳过无效环境变量模型条目: %s",+ exc,+ )+if not self._model_cache:raise ValueError("No valid model entries found in config — all entries failed validation. "diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.pyindex c7eec65a2f..2c2c46ed98 100644--- a/jiuwenswarm/server/runtime/agent_manager.py+++ b/jiuwenswarm/server/runtime/agent_manager.py@@ -67,6 +67,19 @@ def _normalize_channel_id(channel_id: str | None) -> str:return str(channel_id or "default").strip() or "default"+def _session_id_prefix_for_channel(channel_id: str | None) -> str:+ """Path-safe session id prefix; may differ from logical ``channel_id``.++ Cron scheduler uses channel ``__cron__`` for routing, but ids like+ ``__cron___{ts}_{uuid}`` fail ``sanitize_session_id`` and cannot be+ used as sessions directory names.+ """+ channel_key = _normalize_channel_id(channel_id)+ if channel_key == "__cron__":+ return "cron"+ return channel_key++def _normalize_mode(mode: str | None) -> str:return str(mode or "agent").strip() or "agent"@@ -765,8 +778,9 @@ class AgentManager:logger.info("[AgentManager] session ensured: channel_id=%s session_id=%s", channel_id, explicit_session_id)return explicit_session_idchannel_key = _normalize_channel_id(channel_id)+ session_prefix = _session_id_prefix_for_channel(channel_id)session_id = (- f"{channel_key}_{int(time.time() * 1000):x}_"+ f"{session_prefix}_{int(time.time() * 1000):x}_"f"{uuid.uuid4().hex[:12]}")logger.info(diff --git a/jiuwenswarm/server/runtime/agent_warm_pool.py b/jiuwenswarm/server/runtime/agent_warm_pool.pyindex 4c5740a40d..ba6e760320 100644--- a/jiuwenswarm/server/runtime/agent_warm_pool.py+++ b/jiuwenswarm/server/runtime/agent_warm_pool.py@@ -214,7 +214,9 @@ class AgentWarmPool:@staticmethoddef _new_session_id(channel_id: str) -> str:- prefix = str(channel_id or "default").strip() or "default"+ from jiuwenswarm.server.runtime.agent_manager import _session_id_prefix_for_channel++ prefix = _session_id_prefix_for_channel(channel_id)return f"{prefix}_{int(time.time() * 1000):x}_{secrets.token_hex(6)}"def _marker_path(self, session_id: str) -> Path:diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex c2716a457a..d048d529aa 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -439,8 +439,8 @@ def get_read_history_path(session_id: str, sessions_root: str | None = None) ->return jsonl_path-def history_exists(session_id: str) -> bool:- return get_read_history_path(session_id).exists()+def history_exists(session_id: str, sessions_root: str | None = None) -> bool:+ return get_read_history_path(session_id, sessions_root=sessions_root).exists()def get_history_mtime(session_id: str) -> float | None:@@ -531,8 +531,8 @@ def _read_history_jsonl(path: Path) -> list[dict[str, Any]]:return records-def load_history_records(session_id: str) -> list[dict[str, Any]]:- return _read_history(get_read_history_path(session_id))+def load_history_records(session_id: str, sessions_root: str | None = None) -> list[dict[str, Any]]:+ return _read_history(get_read_history_path(session_id, sessions_root=sessions_root))def _write_records_to_path(path: Path, records: list[dict[str, Any]]) -> None:diff --git a/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py b/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.pyindex 524d5b5d46..b4f6deb531 100644--- a/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py+++ b/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py@@ -121,9 +121,13 @@ async def test_concurrent_get_agent_creates_one_cached_root() -> None:@pytest.mark.asyncioasync def test_same_key_creation_waits_for_old_root_cleanup() -> None:+ from jiuwenswarm.server.runtime.agent_manager import _make_agent_cache_key+manager = _SlowCreateAgentManager()old_agent = _BlockingRootCleanupAgent()- cache_key = "code:normal:/tmp/shared-project"+ # 与 get_agent 内部使用相同的缓存 key 生成逻辑,避免 Windows 下路径+ # 规范化(normcase/abspath)后 key 不匹配、创建锁无法复用。+ cache_key = _make_agent_cache_key("code", "normal", "/tmp/shared-project")manager.agents["tui"] = {cache_key: old_agent}cleanup_task = asyncio.create_task(@@ -306,3 +310,17 @@ async def test_cleanup_session_runtime_rejects_retained_session_state() -> None:channel_id="tui",session_id="tui_busy_session",)+++async def test_create_session_cron_channel_uses_path_safe_prefix() -> None:+ from jiuwenswarm.server.runtime.prompt_attachment_loader import sanitize_session_id+ from jiuwenswarm.server.runtime.session.session_metadata import resolve_session_subdir++ manager = AgentManager()+ session_id = await manager.create_session(channel_id="__cron__")++ assert session_id.startswith("cron_")+ assert not session_id.startswith("__cron__")+ assert sanitize_session_id(session_id) == session_id+ assert resolve_session_subdir(session_id) is not Nonediff --git a/tests/unit_tests/agentserver/test_cron_tenant_scope.py b/tests/unit_tests/agentserver/test_cron_tenant_scope.pyindex e8237ed02c..3fbf38ad0f 100644--- a/tests/unit_tests/agentserver/test_cron_tenant_scope.py+++ b/tests/unit_tests/agentserver/test_cron_tenant_scope.py@@ -9,13 +9,16 @@ from jiuwenswarm.agents.harness.common.tools.cron.cron_tools import (resolve_cron_jobs_path,)from jiuwenswarm.server.runtime.cron_local_runtime import AgentCronRegistry-from tests.unit_tests.tenant_workspace_test_helpers import (- patch_multi_tenant_workspace_dirs,-)def test_resolve_cron_jobs_path_isolates_tenants(tmp_path, monkeypatch):- patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)+ # 多租户分桶是企业版语义;个人版固定 service_default/agent_default。+ # cron_tools 模块级 import 绑定了 get_multi_tenant_user_workspace_dir,+ # 需 patch utils 内的 is_enterprise/get_user_workspace_dir 让旧函数对象走分桶。+ monkeypatch.setattr("jiuwenswarm.common.utils.is_enterprise", lambda: True)+ monkeypatch.setattr(+ "jiuwenswarm.common.utils.get_user_workspace_dir", lambda: tmp_path+ )office = resolve_cron_jobs_path("default", "office", workspace_key="office")default = resolve_cron_jobs_path("default", "default", workspace_key="default")assert office != default@@ -25,7 +28,10 @@ def test_resolve_cron_jobs_path_isolates_tenants(tmp_path, monkeypatch):def test_cron_tools_store_path_follows_tenant(tmp_path, monkeypatch):- patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)+ monkeypatch.setattr("jiuwenswarm.common.utils.is_enterprise", lambda: True)+ monkeypatch.setattr(+ "jiuwenswarm.common.utils.get_user_workspace_dir", lambda: tmp_path+ )AgentCronRegistry.reset_for_tests()tools = CronTools(service_id="svc", agent_id="office", workspace_key="office")assert "workspace_office" in str(tools._local_store.path)diff --git a/tests/unit_tests/agentserver/test_history_payload_limits.py b/tests/unit_tests/agentserver/test_history_payload_limits.pyindex e5751aaaab..150b19fdc8 100644--- a/tests/unit_tests/agentserver/test_history_payload_limits.py+++ b/tests/unit_tests/agentserver/test_history_payload_limits.py@@ -158,11 +158,15 @@ def test_history_get_sanitizes_large_restorable_records(monkeypatch):},}- monkeypatch.setattr(session_handlers, "history_exists", lambda session_id: True)+ monkeypatch.setattr(+ session_handlers,+ "history_exists",+ lambda session_id, sessions_root=None: True,+ )monkeypatch.setattr(session_handlers,"load_history_records",- lambda session_id: [large_record],+ lambda session_id, sessions_root=None: [large_record],)result = session_handlers.get_conversation_history(diff --git a/tests/unit_tests/agentserver/test_tenant_sessions_write.py b/tests/unit_tests/agentserver/test_tenant_sessions_write.pyindex 4fc0c94f67..1a22a189da 100644--- a/tests/unit_tests/agentserver/test_tenant_sessions_write.py+++ b/tests/unit_tests/agentserver/test_tenant_sessions_write.py@@ -26,6 +26,8 @@ def test_resolve_tenant_sessions_dir_layout(tmp_path, monkeypatch):"jiuwenswarm.common.utils.get_user_workspace_dir",lambda: tmp_path,)+ # 多租户分桶是企业版语义;个人版固定 service_default/agent_default。+ monkeypatch.setattr("jiuwenswarm.common.utils.is_enterprise", lambda: True)path = resolve_tenant_sessions_dir("office")assert path == tmp_path / "workspace_office" / "agent" / "sessions"@@ -74,6 +76,8 @@ def test_cache_isolated_by_sessions_root(tmp_path, monkeypatch):"jiuwenswarm.common.utils.get_user_workspace_dir",lambda: tmp_path,)+ # 多租户分桶是企业版语义;个人版固定目录会使不同 key 落到同一 sessions_root。+ monkeypatch.setattr("jiuwenswarm.common.utils.is_enterprise", lambda: True)global_sessions = tmp_path / "workspace_default" / "agent" / "sessions"global_sessions.mkdir(parents=True)monkeypatch.setattr(diff --git a/tests/unit_tests/gateway/test_cron_db_schedule.py b/tests/unit_tests/gateway/test_cron_db_schedule.pynew file mode 100644index 0000000000..199d52ff2c--- /dev/null+++ b/tests/unit_tests/gateway/test_cron_db_schedule.py@@ -0,0 +1,219 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++from datetime import datetime, timedelta+from unittest.mock import AsyncMock, MagicMock++import pytest+from zoneinfo import ZoneInfo++from jiuwenswarm.gateway.cron.db_schedule import (+ claim_oneshot_run,+ claim_periodic_run,+ compute_next_push_dt,+ datetime_to_db_value,+ fire_at_from_run_id,+ is_oneshot_job,+ next_run_at_to_datetime,+)+from jiuwenswarm.gateway.cron.models import CronJob+++def _job(**overrides: object) -> CronJob:+ base = {+ "id": "job-1",+ "name": "test",+ "enabled": True,+ "expired": False,+ "cron_expr": "0 * * * *",+ "timezone": "Asia/Shanghai",+ "description": "desc",+ "targets": "web",+ "delete_after_run": False,+ }+ base.update(overrides)+ return CronJob.from_dict(base)+++def test_is_oneshot_job() -> None:+ assert not is_oneshot_job(_job())+ assert is_oneshot_job(_job(delete_after_run=True))+++def test_next_run_at_roundtrip_epoch() -> None:+ tz = ZoneInfo("Asia/Shanghai")+ push_dt = datetime(2026, 8, 31, 12, 0, 0, tzinfo=tz)+ job = _job(next_run_at=push_dt.timestamp())+ parsed = next_run_at_to_datetime(job)+ assert parsed is not None+ assert int(parsed.timestamp()) == int(push_dt.timestamp())+++def test_fire_at_from_run_id() -> None:+ tz = ZoneInfo("Asia/Shanghai")+ push_dt = datetime(2026, 8, 31, 12, 0, 0, tzinfo=tz)+ run_id = f"job-1:{int(push_dt.timestamp())}"+ job = _job()+ fire_at = fire_at_from_run_id(run_id, job)+ assert fire_at is not None+ assert int(fire_at.timestamp()) == int(push_dt.timestamp())+++async def test_claim_periodic_success(monkeypatch: pytest.MonkeyPatch) -> None:+ job = _job()+ tz = ZoneInfo("Asia/Shanghai")+ # 使用未来整点作为 fire_at:compute_next_push_after_fire 会把过期时间兜底为+ # 当前时间,若 fire_at 是过去时刻会导致 next_run_at 断言随时间漂移。+ fire_at = (datetime.now(tz) + timedelta(hours=1)).replace(+ minute=0, second=0, microsecond=0,+ )+ next_push = compute_next_push_dt(job.cron_expr, job.timezone, base=fire_at)++ execute = AsyncMock(return_value=1)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.db_schedule._execute_claim_sql",+ execute,+ )++ ok = await claim_periodic_run(job, fire_at)+ assert ok is True+ assert execute.await_count == 1+ sql = execute.await_args.args[0]+ assert "UPDATE cron_job" in sql+ params = execute.await_args.args[1]+ assert params["job_id"] == "job-1"+ assert params["fire_at"] == datetime_to_db_value(fire_at)+ assert params["next_run_at"] == datetime_to_db_value(next_push)+++async def test_claim_periodic_miss(monkeypatch: pytest.MonkeyPatch) -> None:+ job = _job()+ tz = ZoneInfo("Asia/Shanghai")+ fire_at = datetime(2026, 8, 31, 12, 0, 0, tzinfo=tz)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.db_schedule._execute_claim_sql",+ AsyncMock(return_value=0),+ )+ ok = await claim_periodic_run(job, fire_at)+ assert ok is False+++async def test_claim_oneshot_expires(monkeypatch: pytest.MonkeyPatch) -> None:+ job = _job(delete_after_run=True)+ tz = ZoneInfo("Asia/Shanghai")+ fire_at = datetime(2026, 8, 31, 12, 0, 0, tzinfo=tz)+ execute = AsyncMock(return_value=1)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.db_schedule._execute_claim_sql",+ execute,+ )+ ok = await claim_oneshot_run(job, fire_at)+ assert ok is True+ sql = execute.await_args.args[0]+ assert "UPDATE cron_job" in sql+ assert "expired = 1" in sql+ assert "enabled = 0" in sql+ assert "DELETE FROM cron_job" not in sql+ params = execute.await_args.args[1]+ assert params["fire_at"] == datetime_to_db_value(fire_at)+ assert params["last_run_at"] == datetime_to_db_value(fire_at)+++async def test_scheduler_claim_wake_db_path(monkeypatch: pytest.MonkeyPatch) -> None:+ from jiuwenswarm.gateway.cron.scheduler import CronSchedulerService++ tz = ZoneInfo("Asia/Shanghai")+ push_dt = datetime(2026, 8, 31, 12, 0, 0, tzinfo=tz)+ job = _job(next_run_at=push_dt.timestamp())+ run_id = f"{job.id}:{int(push_dt.timestamp())}"++ store = MagicMock()+ svc = CronSchedulerService(+ store=store,+ agent_client=MagicMock(),+ message_handler=MagicMock(),+ )+ claim = AsyncMock(return_value=True)+ monkeypatch.setattr(svc, "_use_db_schedule", lambda: True)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.db_schedule.claim_periodic_run",+ claim,+ )+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.db_schedule.fire_at_from_run_id",+ lambda _rid, _job: push_dt,+ )+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.db_schedule.is_oneshot_job",+ lambda _job: False,+ )+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.db_schedule.compute_next_push_after_fire",+ lambda _job, _fire: push_dt,+ )++ ok = await svc._claim_wake(job, run_id)+ assert ok is True+ assert run_id in svc._claimed_run_ids+ claim.assert_awaited_once()+++async def test_scheduler_claim_wake_bypasses_db_for_manual_run_now(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jiuwenswarm.gateway.cron.models import CronRunState+ from jiuwenswarm.gateway.cron.scheduler import CronSchedulerService++ tz = ZoneInfo("Asia/Shanghai")+ push_dt = datetime(2026, 8, 31, 12, 0, 0, tzinfo=tz)+ job = _job(next_run_at=push_dt.timestamp() + 3600)+ run_id = f"{job.id}:{int(datetime.now(tz=tz).timestamp())}"++ store = MagicMock()+ svc = CronSchedulerService(+ store=store,+ agent_client=MagicMock(),+ message_handler=MagicMock(),+ )+ claim = AsyncMock(return_value=True)+ monkeypatch.setattr(svc, "_use_db_schedule", lambda: True)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.db_schedule.claim_periodic_run",+ claim,+ )+ svc._runs[run_id] = CronRunState(+ run_id=run_id,+ job_id=job.id,+ wake_at_iso=push_dt.isoformat(),+ push_at_iso=push_dt.isoformat(),+ manual_trigger=True,+ )++ ok = await svc._claim_wake(job, run_id)+ assert ok is True+ assert run_id in svc._claimed_run_ids+ claim.assert_not_awaited()+++def test_should_use_db_schedule(monkeypatch: pytest.MonkeyPatch) -> None:+ from jiuwenswarm.gateway.cron.db_schedule import should_use_db_schedule++ monkeypatch.delenv("GATEWAY_DB_HOST", raising=False)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.enterprise_gate.enterprise_cron_enabled",+ lambda: False,+ )+ assert should_use_db_schedule() is False++ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.enterprise_gate.enterprise_cron_enabled",+ lambda: True,+ )+ monkeypatch.setenv("GATEWAY_DB_HOST", "mysql-headless.default")+ assert should_use_db_schedule() is Truediff --git a/tests/unit_tests/gateway/test_cron_tenant_registry.py b/tests/unit_tests/gateway/test_cron_tenant_registry.pyindex 7004222093..a3cb0a9418 100644--- a/tests/unit_tests/gateway/test_cron_tenant_registry.py+++ b/tests/unit_tests/gateway/test_cron_tenant_registry.py@@ -9,6 +9,7 @@ import pytestfrom jiuwenswarm.common.utils import resolve_gateway_cron_jobs_pathfrom tests.unit_tests.tenant_workspace_test_helpers import (+ patch_multi_tenant_workspace_dirs,tenant_workspace_key,tenant_workspace_root,)@@ -103,6 +104,9 @@ async def test_web_create_mirrors_to_agent_home(tmp_path, monkeypatch) -> None:monkeypatch.setattr("jiuwenswarm.common.utils.get_user_workspace_dir", lambda: tmp_path)+ # mirror 路径经 get_multi_tenant_user_workspace_dir 解析,须一并 patch,+ # 否则非企业环境下会落到 service_default/agent_default 固定目录。+ patch_multi_tenant_workspace_dirs(monkeypatch, tmp_path)monkeypatch.setattr("jiuwenswarm.gateway.cron.tenant_registry.CronSchedulerService.start",AsyncMock(),diff --git a/tests/unit_tests/gateway/test_enterprise_cron_gate.py b/tests/unit_tests/gateway/test_enterprise_cron_gate.pyindex 1c538cb05c..39eccf0a64 100644--- a/tests/unit_tests/gateway/test_enterprise_cron_gate.py+++ b/tests/unit_tests/gateway/test_enterprise_cron_gate.py@@ -152,7 +152,10 @@ def test_enterprise_cron_enabled_by_deployment_mode() -> None:monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")assert enterprise_cron_enabled(deployment_mode="standalone") is True+ monkeypatch.delenv("GATEWAY_DB_HOST", raising=False)assert enterprise_cron_enabled(deployment_mode="distributed") is False+ monkeypatch.setenv("GATEWAY_DB_HOST", "mysql-headless.default")+ assert enterprise_cron_enabled(deployment_mode="distributed") is Truedef test_enterprise_cron_disabled_for_personal_edition(diff --git a/tests/unit_tests/test_project_handlers.py b/tests/unit_tests/test_project_handlers.pyindex c25a6fb817..d93ebc9566 100644--- a/tests/unit_tests/test_project_handlers.py+++ b/tests/unit_tests/test_project_handlers.py@@ -949,4 +949,174 @@ class TestSessionCreateProjectDirConsistency:resp = await _call(registered_channel, "session.create", params)assert resp["ok"] is Falseassert resp["code"] == "BAD_REQUEST"+++# ===========================================================================+# project.get_cron_sessions (remote → Agent session.list)+# ===========================================================================+class _FakeSessionListAgentClient:+ def __init__(self, sessions: list[dict]):+ self._sessions = sessions+ self.requests: list[object] = []++ async def send_request(self, request):+ self.requests.append(request)+ params = dict(request.params or {})+ limit = int(params.get("limit", 200))+ offset = int(params.get("offset", 0))+ batch = self._sessions[offset:offset + limit]+ return SimpleNamespace(+ ok=True,+ payload={+ "sessions": batch,+ "total": len(self._sessions),+ "limit": limit,+ "offset": offset,+ },+ )+++class TestProjectGetCronSessionsRemote:+ @staticmethod+ @pytest.mark.asyncio+ async def test_remote_mode_fetches_and_filters_cron_sessions(+ registered_channel, tmp_path, monkeypatch,+ ):+ """remote 存储:从 Agent session.list 拉全量,再按 cron_id / 项目过滤。"""+ monkeypatch.setattr(+ "jiuwenswarm.gateway.routing.session_index.is_remote_storage",+ lambda: True,+ )++ pa = _abspath(tmp_path, "cron_app")+ proj = _make_project("CronApp", pa)+ agent_sessions = [+ {+ "session_id": "cron_run_1",+ "cron_id": "job-abc",+ "project_id": proj.project_id,+ "project_dir": pa,+ "channel_id": "__cron__",+ "last_user_message_at": 200.0,+ "title": "cron run",+ "created_at": 1.0,+ "last_message_at": 200.0,+ "message_count": 1,+ "mode": "agent",+ "team_name": "",+ "pinned": False,+ "pin_order": 0,+ "model": "",+ "work_mode": "work",+ },+ {+ "session_id": "web_normal",+ "cron_id": "",+ "project_id": proj.project_id,+ "project_dir": pa,+ "channel_id": "web",+ "last_user_message_at": 300.0,+ "title": "normal",+ "created_at": 1.0,+ "last_message_at": 300.0,+ "message_count": 1,+ "mode": "agent",+ "team_name": "",+ "pinned": False,+ "pin_order": 0,+ "model": "",+ "work_mode": "work",+ },+ {+ "session_id": "cron_other_job",+ "cron_id": "job-other",+ "project_id": proj.project_id,+ "project_dir": pa,+ "channel_id": "__cron__",+ "last_user_message_at": 100.0,+ "title": "other cron",+ "created_at": 1.0,+ "last_message_at": 100.0,+ "message_count": 1,+ "mode": "agent",+ "team_name": "",+ "pinned": False,+ "pin_order": 0,+ "model": "",+ "work_mode": "work",+ },+ ]+ from jiuwenswarm.gateway.channel_manager.web.app_web_handlers import (+ WebHandlersBindParams,+ _register_web_handlers,+ )++ fake_client = _FakeSessionListAgentClient(agent_sessions)+ # handler 在注册时捕获 agent_client,需重新注册以注入 fake session.list 客户端+ _register_web_handlers(+ WebHandlersBindParams(channel=registered_channel, agent_client=fake_client)+ )++ resp = await _call(+ registered_channel,+ "project.get_cron_sessions",+ {"project_id": proj.project_id, "cron_id": "job-abc"},+ )+ assert resp["ok"] is True+ sessions = resp["payload"]["sessions"]+ assert len(sessions) == 1+ assert sessions[0]["session_id"] == "cron_run_1"+ assert sessions[0]["cron_id"] == "job-abc"+ assert fake_client.requests++ @staticmethod+ @pytest.mark.asyncio+ async def test_remote_mode_paginates_session_list(registered_channel, sessions_dir, monkeypatch):+ """remote 存储:超过单页上限时循环拉取 session.list。"""+ monkeypatch.setattr(+ "jiuwenswarm.gateway.routing.session_index.is_remote_storage",+ lambda: True,+ )+ from jiuwenswarm.gateway.channel_manager.web.app_web_handlers import _SESSION_LIST_PAGE_SIZE++ agent_sessions = [+ {+ "session_id": f"cron_{i}",+ "cron_id": "job-paged",+ "project_id": "",+ "project_dir": "",+ "channel_id": "__cron__",+ "last_user_message_at": float(i),+ "title": "",+ "created_at": 0.0,+ "last_message_at": float(i),+ "message_count": 0,+ "mode": "agent",+ "team_name": "",+ "pinned": False,+ "pin_order": 0,+ "model": "",+ "work_mode": "work",+ }+ for i in range(_SESSION_LIST_PAGE_SIZE + 3)+ ]+ from jiuwenswarm.gateway.channel_manager.web.app_web_handlers import (+ WebHandlersBindParams,+ _register_web_handlers,+ )++ fake_client = _FakeSessionListAgentClient(agent_sessions)+ # handler 在注册时捕获 agent_client,需重新注册以注入 fake session.list 客户端+ _register_web_handlers(+ WebHandlersBindParams(channel=registered_channel, agent_client=fake_client)+ )++ resp = await _call(+ registered_channel,+ "project.get_cron_sessions",+ {"project_id": "default", "cron_id": "job-paged"},+ )+ assert resp["ok"] is True+ assert resp["payload"]["total"] == _SESSION_LIST_PAGE_SIZE + 3+ assert len(fake_client.requests) >= 2assert not any(sessions_dir.iterdir())diff --git a/tests/unit_tests/test_web_http_settings_handlers.py b/tests/unit_tests/test_web_http_settings_handlers.pyindex c43fc32b86..e6ded1a2cd 100644--- a/tests/unit_tests/test_web_http_settings_handlers.py+++ b/tests/unit_tests/test_web_http_settings_handlers.py@@ -268,3 +268,75 @@ def test_cron_job_full_path():r = client.post("/api/v1/cron/jobs/missing/actions/toggle", json={})assert r.status_code == 400assert r.json()["error"]["message"] == "enabled is required"+++class _FakeCronRegistry:+ def __init__(self, cron: _FakeCron) -> None:+ self.cron = cron+ self.toggle_kwargs: list[dict] = []++ async def get_controller(self, service_id: str, agent_id: str):+ return self.cron++ async def web_toggle_job(+ self,+ job_id: str,+ enabled: bool,+ service_id: str,+ agent_id: str,+ *,+ group_id: str | None = None,+ bot_id: str | None = None,+ user_id: str | None = None,+ ) -> dict:+ self.toggle_kwargs.append(+ {+ "job_id": job_id,+ "enabled": enabled,+ "service_id": service_id,+ "agent_id": agent_id,+ "group_id": group_id,+ "bot_id": bot_id,+ "user_id": user_id,+ }+ )+ return await self.cron.toggle_job(+ job_id,+ enabled,+ group_id=group_id,+ bot_id=bot_id,+ user_id=user_id,+ )+++def test_cron_job_toggle_passes_routing_triple_to_registry():+ cron = _FakeCron()+ registry = _FakeCronRegistry(cron)+ channel = WebChannel(WebChannelConfig(host="127.0.0.1", port=0), RobotMessageRouter())+ _register_web_handlers(+ WebHandlersBindParams(channel=channel, cron_controller=cron, cron_registry=registry),+ )+ client = TestClient(create_web_http_app(channel))++ r = client.post(+ "/api/v1/cron/jobs/job-1/actions/toggle",+ json={"enabled": True},+ headers={+ "X-Group-Id": "g1",+ "X-Bot-Id": "b1",+ "X-User-Id": "u1",+ },+ )+ assert r.status_code == 200+ assert r.json()["data"]["job"]["enabled"] is True+ assert registry.toggle_kwargs == [+ {+ "job_id": "job-1",+ "enabled": True,+ "service_id": "default",+ "agent_id": "default",+ "group_id": "g1",+ "bot_id": "b1",+ "user_id": "u1",+ }+ ]