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(proactive recommendation): format check for max recommendation per day and max dialogue turn used
Haowei_Du59cf6de704a6
diff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.pyindex ad0b42b8da..fb2db0b8ae 100644--- a/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py@@ -22,6 +22,7 @@ Usage:from __future__ import annotationsimport logging+import reimport timefrom typing import Any@@ -29,6 +30,35 @@ from typing import Anylogger = logging.getLogger(__name__)+# proactive 数值配置项的合法区间(与 web handler _validate_proactive_int 保持一致)。+_PROACTIVE_INT_LO = 1+_PROACTIVE_INT_HI = 50+++def _safe_proactive_int(val: Any, default: int) -> int:+ """读取 proactive 数值配置项的防御性解析。++ config.yaml 被手改成非数字/浮点/超范围时,降级用 default + warning,不让引擎崩溃。+ (handler 写入时已校验,这里只防手改 config / 旧脏数据。)+ """+ # 先按字符串校验:挡住浮点(3.5)、科学计数(1e5)、字符串(abc)、空。+ # int(3.5) 在 Python 会静默截断成 3,不能直接 int()。+ raw = str(val).strip() if val is not None else ""+ if not re.fullmatch(r"[0-9]+", raw):+ logger.warning(+ "[ProactiveEngine] invalid int config %r, fallback to default %d", val, default,+ )+ return default+ n = int(raw)+ if n < _PROACTIVE_INT_LO or n > _PROACTIVE_INT_HI:+ logger.warning(+ "[ProactiveEngine] int config %r out of [%d,%d], fallback to default %d",+ val, _PROACTIVE_INT_LO, _PROACTIVE_INT_HI, default,+ )+ return default+ return n++class ProactiveEngine:"""Proactive recommendation engine service.@@ -46,8 +76,8 @@ class ProactiveEngine:def __init__(self, config: dict[str, Any] | None = None) -> None:config = config or {}- self._max_per_day: int = int(config.get("max_recommend_per_day", 5))- self._max_rounds: int = int(config.get("max_rounds_per_tick", 20))+ self._max_per_day: int = _safe_proactive_int(config.get("max_recommend_per_day", 5), 5)+ self._max_rounds: int = _safe_proactive_int(config.get("max_rounds_per_tick", 20), 20)# 默认 False,与 config.yaml 的 proactive_recommendation.enabled 默认值一致,# 防御性默认=关闭,避免配置段缺失时引擎被误启用。self._enabled: bool = config.get("enabled", False)@@ -116,8 +146,8 @@ class ProactiveEngine:def reload_config(self, config: dict[str, Any]) -> None:"""Hot-reload configuration without restarting the process."""new_enabled = bool(config.get("enabled", False))- new_max_per_day = int(config.get("max_recommend_per_day", self._max_per_day))- new_max_rounds = int(config.get("max_rounds_per_tick", self._max_rounds))+ new_max_per_day = _safe_proactive_int(config.get("max_recommend_per_day", self._max_per_day), self._max_per_day)+ new_max_rounds = _safe_proactive_int(config.get("max_rounds_per_tick", self._max_rounds), self._max_rounds)self._max_per_day = new_max_per_dayself._max_rounds = new_max_roundsdiff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsxindex 42bca2f7bc..917acecab0 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx@@ -536,6 +536,43 @@ function isBooleanKey(key: string): boolean {);}+// proactive 数值配置项:只接受 1-50 的正整数。+// 与后端 web handler _validate_proactive_int 保持一致。+interface ProactiveIntSpec {+ lo: number;+ hi: number;+ labelKey: string;+}+const PROACTIVE_INT_SPECS: Record<string, ProactiveIntSpec> = {+ proactive_recommendation_max_recommend_per_day: {+ lo: 1, hi: 50, labelKey: "config.keys.proactiveMaxPerDay",+ },+ proactive_recommendation_max_rounds_per_tick: {+ lo: 1, hi: 50, labelKey: "config.keys.proactiveMaxRounds",+ },+};++function validateProactiveInt(+ key: string, raw: string, t: (k: string, opts?: Record<string, unknown>) => string,+): string | null {+ const spec = PROACTIVE_INT_SPECS[key];+ if (!spec) return null;+ const field = t(spec.labelKey);+ const s = (raw ?? "").trim();+ if (!s) {+ return t("config.errors.proactiveIntEmpty", { field, lo: spec.lo, hi: spec.hi });+ }+ // 正则一次挡住浮点(3.5)、负数(-1)、科学计数(1e5)、字符串(abc)+ if (!/^[0-9]+$/.test(s)) {+ return t("config.errors.proactiveIntNotInteger", { field, value: s, lo: spec.lo, hi: spec.hi });+ }+ const n = parseInt(s, 10);+ if (n < spec.lo || n > spec.hi) {+ return t("config.errors.proactiveIntOutOfRange", { field, lo: spec.lo, hi: spec.hi, value: n });+ }+ return null;+}+function parseBoolValue(value: string): boolean {return value.toLowerCase() === "true" || value === "1";}@@ -792,6 +829,12 @@ function GroupSection({{getKeyLabelHintText(key, t)}</div>) : null}+ {PROACTIVE_INT_SPECS[key] ? (() => {+ const e = validateProactiveInt(key, draftValues[key] ?? "", t);+ return e ? (+ <div className="mt-1 text-[11px] leading-4 text-danger">{e}</div>+ ) : null;+ })() : null}</td><td className="px-4 py-2.5 break-all text-[13px] align-middle">{isBooleanKey(key) ? (@@ -3181,6 +3224,18 @@ export function ConfigPanel({return;}+ // proactive 数值配置项提交校验:只校验有改动的,挡住负数/浮点/字符串/超范围+ for (const key of Object.keys(PROACTIVE_INT_SPECS)) {+ if (key in configUpdates) {+ const err = validateProactiveInt(key, configUpdates[key], t);+ if (err) {+ setConfigTab("other");+ setError(err);+ return;+ }+ }+ }+setSaving(true);setError(null);setModelError(null);diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsxindex b0a677fc49..6c8b62458d 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx@@ -12,8 +12,8 @@ import { useSessionStore } from '../../stores/sessionStore';const DEFAULT_CRON_TIMEZONE = 'Asia/Shanghai';const DEFAULT_CRON_TARGET = 'web';// 由主动推荐配置自动维护的 job id(与后端 proactive_cron_sync.PROACTIVE_JOB_ID 一致)。-// 该 job 的调度表达式随 proactive_recommendation.tick_interval_minutes 变化,-// 面板上对其禁用编辑/删除,频率调整走设置→主动推荐。+// 该 job 的整体开关由 config 的 proactive_recommendation.enabled 驱动(关则删除,不在列表里),+// 面板上禁用 启停/删除;编辑时仅 cron 表达式与时区可改,其余字段(名称/状态/描述/偏移/频道)只读。const PROACTIVE_AUTO_JOB_ID = 'proactive-tick-auto';interface CronJob {@@ -525,9 +525,13 @@ export default function CronPanel({ sessionId }: CronPanelProps) {// 否则会被会话 mode(agent.plan)覆盖,导致走普通 cron 流程而非引擎。// 不带 wake_offset_seconds——proactive.tick 到点就执行,偏移由后端强制 0。if (jobId === PROACTIVE_AUTO_JOB_ID) {+ // proactive job 只允许改 cron_expr 和 timezone,其余由 ConfigPanel/cron_sync 管delete patch['enabled'];delete patch['mode'];delete patch['wake_offset_seconds'];+ delete patch['name'];+ delete patch['description'];+ delete patch['targets'];}const updateData: Record<string, unknown> = {id: editJob.id,@@ -758,7 +762,8 @@ export default function CronPanel({ sessionId }: CronPanelProps) {...prev,[job.id]: { ...prev[job.id], name: e.target.value },}))}- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"+ disabled={job.id === PROACTIVE_AUTO_JOB_ID}+ className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : ''}`}placeholder={t('cron.placeholders.name')}/></td>@@ -812,7 +817,8 @@ export default function CronPanel({ sessionId }: CronPanelProps) {...prev,[job.id]: { ...prev[job.id], description: e.target.value },}))}- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"+ disabled={job.id === PROACTIVE_AUTO_JOB_ID}+ className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : ''}`}placeholder={t('cron.placeholders.description')}/></td>@@ -852,7 +858,8 @@ export default function CronPanel({ sessionId }: CronPanelProps) {...prev,[job.id]: { ...prev[job.id], targets: e.target.value },}))}- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"+ disabled={job.id === PROACTIVE_AUTO_JOB_ID}+ className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : ''}`}>{targetOptions.map((option) => (<option key={option.value} value={option.value} disabled={option.disabled}>@@ -909,13 +916,22 @@ export default function CronPanel({ sessionId }: CronPanelProps) {{displayCron}</td><td className="px-4 py-3">- <span- className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${- job.expired ? 'bg-amber-100 text-amber-700' : job.enabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'- }`}- >- {job.expired ? t('cron.status.expired') : job.enabled ? t('cron.status.enabled') : t('cron.status.disabled')}- </span>+ {(() => {+ // proactive 自动维护 job 的整体开关由 config 控制(关了就删除,不在列表里),+ // 因此状态只有两态:cron 过期 → 过期;否则 → 启用。不显示"禁用"中间态。+ const isProactiveRow = job.id === PROACTIVE_AUTO_JOB_ID;+ const isExpired = Boolean(job.expired);+ const isEnabled = isProactiveRow ? !isExpired : Boolean(job.enabled);+ return (+ <span+ className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${+ isExpired ? 'bg-amber-100 text-amber-700' : isEnabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'+ }`}+ >+ {isExpired ? t('cron.status.expired') : isEnabled ? t('cron.status.enabled') : t('cron.status.disabled')}+ </span>+ );+ })()}</td><td className="px-4 py-3 text-sm text-text-muted"><div className="max-w-[300px] overflow-hidden text-ellipsis whitespace-nowrap" title={displayDescription || '-'}>diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 6505c7e1e6..584095ff72 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -879,7 +879,10 @@"errors": {"requiredModelFields": "These model fields are required: {{fields}}. Complete them before saving and restarting.","saveFailed": "Save failed, please try again later",- "processingDisabled": "A task is running. Please wait for it to finish before saving config."+ "processingDisabled": "A task is running. Please wait for it to finish before saving config.",+ "proactiveIntEmpty": "{{field}} cannot be empty; must be a positive integer ({{lo}}-{{hi}})",+ "proactiveIntNotInteger": "{{field}} must be a positive integer ({{lo}}-{{hi}}); invalid value: {{value}}",+ "proactiveIntOutOfRange": "{{field}} must be a positive integer in {{lo}}-{{hi}}; current: {{value}}"}},"cron": {@@ -898,7 +901,7 @@"empty": "No scheduled tasks","deleteConfirm": "Are you sure you want to delete this task?","autoManaged": "Auto-managed",- "autoManagedHint": "This task is auto-created/deleted by the proactive recommendation toggle (Settings → Proactive Recommendation). Schedule, offset, timezone and target channel can be edited here; to remove it, turn off the toggle in Settings.",+ "autoManagedHint": "This task is auto-created/deleted by the proactive recommendation toggle (Settings → Proactive Recommendation). Only the cron expression and timezone can be edited here; other fields (name/status/description/offset/channel) are read-only. To remove it, turn off the toggle in Settings.","autoManagedToggleDisabled": "The toggle of an auto-managed task is controlled by Settings → Proactive Recommendation and cannot be switched here.","status": {"enabled": "Enabled",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex fde3434039..4768f7c723 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -878,7 +878,10 @@"errors": {"requiredModelFields": "模型配置为必填:{{fields}}。请完整填写后再保存并重启。","saveFailed": "保存失败,请稍后重试",- "processingDisabled": "任务执行中,请等待任务完成后再保存配置。"+ "processingDisabled": "任务执行中,请等待任务完成后再保存配置。",+ "proactiveIntEmpty": "{{field}} 不能为空,需为 {{lo}}-{{hi}} 的正整数",+ "proactiveIntNotInteger": "{{field}} 必须是正整数({{lo}}-{{hi}}),当前值无效:{{value}}",+ "proactiveIntOutOfRange": "{{field}} 需为 {{lo}}-{{hi}} 的正整数,当前:{{value}}"}},"cron": {@@ -897,7 +900,7 @@"empty": "暂无定时任务","deleteConfirm": "确定要删除这个任务吗?","autoManaged": "自动维护",- "autoManagedHint": "此任务由主动推荐开关自动创建/删除;开关在设置→主动推荐。调度频率、偏移、时区、推送频道可在此面板编辑,删除请到设置关闭开关。",+ "autoManagedHint": "此任务由主动推荐开关自动创建/删除;开关在设置→主动推荐。仅 Cron 表达式与时区可在此面板编辑,其余字段(名称/状态/描述/偏移/频道)不可改;删除请到设置关闭开关。","autoManagedToggleDisabled": "自动维护任务的开关由设置→主动推荐控制,不可在此切换。","status": {"enabled": "启用",diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex c32a4f4d60..15fdff665c 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1206,6 +1206,27 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:class _ConfigInternalError(RuntimeError):pass+ def _validate_proactive_int(+ val: Any, *, name: str, lo: int = 1, hi: int = 50,+ ) -> int:+ """校验 proactive 数值配置项:必须是 [lo, hi] 的正整数字符串。++ 挡住负数、零、浮点数(3.5)、字符串(abc)、科学计数(1e5)、空值。+ 校验失败抛 _ConfigBadRequest(携带中文提示),由外层返回前端。+ """+ raw = str(val if val is not None else "").strip()+ if not raw:+ raise _ConfigBadRequest(f"{name} 不能为空,需为 {lo}-{hi} 的正整数")+ # 正则一次挡住浮点、负数、科学计数、非数字+ if not re.fullmatch(r"[0-9]+", raw):+ raise _ConfigBadRequest(+ f"{name} 必须是正整数({lo}-{hi}),当前值无效:{raw!r}"+ )+ n = int(raw)+ if n < lo or n > hi:+ raise _ConfigBadRequest(f"{name} 需为 {lo}-{hi} 的正整数,当前:{n}")+ return n+def _encrypt_config_params(params: dict[str, Any]) -> dict[str, Any]:encrypted = dict(params)for key, val in list(encrypted.items()):@@ -1273,10 +1294,15 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:elif param_key == "proactive_recommendation_enabled":update_proactive_recommendation_in_config({"enabled": parsed})elif param_key == "proactive_recommendation_max_recommend_per_day":- update_proactive_recommendation_in_config({"max_recommend_per_day": int(str(val).strip())})+ n = _validate_proactive_int(val, name="每日推荐上限(max_recommend_per_day)")+ update_proactive_recommendation_in_config({"max_recommend_per_day": n})elif param_key == "proactive_recommendation_max_rounds_per_tick":- update_proactive_recommendation_in_config({"max_rounds_per_tick": int(str(val).strip())})+ n = _validate_proactive_int(val, name="每次检查对话轮数(max_rounds_per_tick)")+ update_proactive_recommendation_in_config({"max_rounds_per_tick": n})yaml_updated.append(param_key)+ except _ConfigBadRequest:+ # proactive 数值校验等:直接返回前端,不被外层吞成 warning+ raiseexcept Exception as e: # noqa: BLE001logger.warning("[config.set] 写回 config.yaml 失败 %s: %s", param_key, e)if param_key == "swarmflow_enabled":@@ -2861,6 +2887,15 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if not job_id:await channel.send_response(ws, req_id, ok=False, error="id is required", code="BAD_REQUEST")return+ # proactive.tick job 由主动推荐开关自动创建/删除,禁止面板删除。+ existing = await cc.get_job(job_id)+ if existing is not None and str(getattr(existing, "mode", "") or "").strip().lower() == "proactive.tick":+ await channel.send_response(+ ws, req_id, ok=False,+ error="主动推荐定时任务由设置→主动推荐开关控制,不能在面板删除;请到设置关闭开关。",+ code="BAD_REQUEST",+ )+ returndeleted = await cc.delete_job(job_id)if not deleted:await channel.send_response(ws, req_id, ok=False, error="job not found", code="NOT_FOUND")@@ -2883,6 +2918,15 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if enabled is None:await channel.send_response(ws, req_id, ok=False, error="enabled is required", code="BAD_REQUEST")return+ # proactive.tick job 的 enabled 由 config 开关驱动,禁止面板手动切换。+ existing = await cc.get_job(job_id)+ if existing is not None and str(getattr(existing, "mode", "") or "").strip().lower() == "proactive.tick":+ await channel.send_response(+ ws, req_id, ok=False,+ error="主动推荐定时任务由设置→主动推荐开关控制,不能在面板启停。",+ code="BAD_REQUEST",+ )+ returntry:job = await cc.toggle_job(job_id, bool(enabled))await channel.send_response(ws, req_id, ok=True, payload={"job": job})diff --git a/jiuwenswarm/gateway/cron/store.py b/jiuwenswarm/gateway/cron/store.pyindex 91e0fbb3f1..fec5d3a3f1 100644--- a/jiuwenswarm/gateway/cron/store.py+++ b/jiuwenswarm/gateway/cron/store.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport json+import loggingimport timeimport uuidfrom dataclasses import replace@@ -17,6 +18,17 @@ from jiuwenswarm.gateway.cron.models import ()from jiuwenswarm.common.utils import get_cron_jobs_path+logger = logging.getLogger(__name__)++# proactive.tick 是由 proactive_cron_sync 自动注册、由 config 开关驱动的任务。+# 其 name/enabled/description/wake_offset/targets/mode 均由系统/配置侧维护,+# update 时只允许改调度本身(cron_expr/timezone);expired/updated_at 由调度器/内部写。+# 用 mode 判断(而非硬编码 id),避免依赖 id 字符串。+_PROACTIVE_TICK_MODE = "proactive.tick"+_PROACTIVE_UPDATE_ALLOWED_KEYS: frozenset[str] = frozenset(+ {"cron_expr", "timezone", "expired", "updated_at"}+)+class CronJobStore:"""Persist cron jobs to ~/.jiuwenswarm/agent/home/cron_jobs.json."""@@ -115,6 +127,18 @@ class CronJobStore:if existing is None:raise KeyError("job not found")+ # proactive.tick job:只接受调度字段(cron_expr/timezone),其余字段一律丢弃,+ # 防止前端或其它调用方改 name/enabled/description/wake_offset/targets/mode 等,+ # 这些字段由 config 开关 / proactive_cron_sync / scheduler 统一维护。+ if str(getattr(existing, "mode", "") or "").strip().lower() == _PROACTIVE_TICK_MODE:+ dropped = [k for k in patch if k not in _PROACTIVE_UPDATE_ALLOWED_KEYS]+ if dropped:+ logger.warning(+ "[CronStore] reject proactive.tick update fields on job=%s: %s (only %s allowed)",+ job_id, ", ".join(dropped), ", ".join(sorted(_PROACTIVE_UPDATE_ALLOWED_KEYS)),+ )+ patch = {k: v for k, v in patch.items() if k in _PROACTIVE_UPDATE_ALLOWED_KEYS}+updated = existingif "name" in patch:updated = replace(updated, name=str(patch.get("name") or "").strip())