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): change the location of notify of proactive recommendation (from session to pop-up window.
Haowei_Du3643312f89c7
diff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.pyindex 6d8c2ee3dc..958d9106be 100644--- a/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.py+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.py@@ -56,32 +56,6 @@ def _prune_daily_counts() -> None:_daily_counts.pop(k, None)-# "今日已达上限"提醒的去重——每天最多推一次,避免 cron 多次到点刷屏。-# 与 _daily_counts 同构:进程内字典 + 当日 key,跨天/重启自动重置。-_limit_notif_lock = threading.Lock()-_limit_notif_sent: dict[str, bool] = {}---def _limit_notif_sent_today() -> bool:- with _limit_notif_lock:- return _limit_notif_sent.get(_today_key(), False)---def _mark_limit_notif_sent() -> None:- with _limit_notif_lock:- _limit_notif_sent[_today_key()] = True---def _prune_limit_notif() -> None:- """Remove entries older than 2 days.(与 _prune_daily_counts 对齐)"""- from datetime import datetime, timedelta, timezone- cutoff = (datetime.now(timezone.utc) - timedelta(days=2)).strftime("%Y-%m-%d")- with _limit_notif_lock:- keys_to_remove = [k for k in _limit_notif_sent if k < cutoff]- for k in keys_to_remove:- _limit_notif_sent.pop(k, None)--# ── Cooldown ─────────────────────────────────────────────────────_COOLDOWN_HOURS = 24@@ -395,6 +369,7 @@ async def _trigger_main_agent(channel_id: str | None,decision: RecommendationDecision,trigger_callback: Any,+ on_delivered: Any = None,) -> bool:"""Trigger the main agent to run one round and generate the recommendation message.@@ -409,8 +384,11 @@ async def _trigger_main_agent(避让:trigger_callback 内部检查 ``is_deep_agent_executing_for_session``,目标 session 正忙时返回 False(跳过本次 tick,下个 tick 再来)。+ ``on_delivered``: fire-and-forget 后台 task 真正跑完(推荐确实送达)时回调。+ 用于让调用方在"推荐确实送达"时再做计数/状态持久化,避免后台失败却已计数。+Returns:- True if the main agent was triggered, False if the session was busy+ True if the main agent was triggered (后台异步跑), False if the session was busyor delivery failed."""query = DIRECTIVE_PROMPT.format(@@ -419,7 +397,8 @@ async def _trigger_main_agent(reason=decision.reason,)try:- return bool(await trigger_callback(session_id, channel_id, query, decision))+ return bool(await trigger_callback(session_id, channel_id, query, decision,+ on_delivered=on_delivered))except Exception as exc:logger.warning("[ProactiveEngine] trigger_main_agent failed: %s", exc, exc_info=True)return False\ No newline at end of filediff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.pyindex 721f1b2664..764fed6aef 100644--- a/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py@@ -149,6 +149,10 @@ class ProactiveEngine: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)+ # 当日推荐计数 _daily_counts 不重置——它是"今天实际推了几条"的客观事实,清掉反而会让+ # 调小上限时 count 归零 < 新上限,在已超额的情况下继续推送,违反上限语义。+ # 上限提醒已改为前端弹窗 + 每次命中都推,无需清任何去重标记。+self._max_per_day = new_max_per_dayself._max_rounds = new_max_roundsself._enabled = new_enabled@@ -201,8 +205,6 @@ class ProactiveEngine:_get_all_skills,_analyze_and_decide,_trigger_main_agent,- _limit_notif_sent_today,- _mark_limit_notif_sent,)from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (load_recommendation_state,@@ -232,17 +234,15 @@ class ProactiveEngine:if _today_recommend_count() >= self._max_per_day:logger.info("[ProactiveEngine] daily limit reached (%d/%d), skipping tick",_today_recommend_count(), self._max_per_day)- # 推送通知提醒用户已到上限——每天最多推一次,避免 cron 多次到点刷屏。- # 用进程内 _limit_notif_sent 当日标记去重;跨天/重启自动重置。- # 推送失败不标记,下次 tick 仍会重试(没送达就不算发过)。- if self._send_notification_callback is not None and not _limit_notif_sent_today():+ # 推送通知提醒用户已到上限。前端拦截 source=proactive_notification 后改走+ # 顶部弹窗(不进会话历史),故这里每次命中上限都推一次,无需去重。+ if self._send_notification_callback is not None:try:await self._send_notification_callback(target_channel,f"今日主动推荐已达每日上限({self._max_per_day} 条),"f"明日恢复。",)- _mark_limit_notif_sent()except Exception as exc:logger.debug("[ProactiveEngine] send_notification failed: %s", exc)self._last_tick_at = time.time()@@ -301,41 +301,49 @@ class ProactiveEngine:return False# ── Step 6: Trigger main agent to generate & deliver ────+ # fire-and-forget:trigger_main_agent 把主 agent 跑一轮丢后台 task,立即返回+ # True(表示"已触发"),让调用方 cron 秒回不超时。Step 7 的状态更新不在+ # 这里立即做,而是包成 on_delivered 回调——后台 task 真正跑完、推荐确实送达+ # 后才回调执行计数/持久化,避免"触发即计数、后台失败却已计数"的名不副实。if self._trigger_main_agent_callback is None:logger.warning("[ProactiveEngine] no trigger_main_agent_callback, skipping")self._last_tick_at = time.time()return False- delivered = await _trigger_main_agent(+ def _on_delivered() -> None:+ """后台送达后才执行的状态更新(Step 7)。"""+ _increment_daily_count()+ _mark_recommended(decision.target, state)+ state.add_recommendation({+ "type": decision.type,+ "target": decision.target,+ "reason": decision.reason,+ "urgency": decision.urgency,+ "tick_at": time.time(),+ "session_id": target_session.session_id,+ })+ state.touch()+ save_recommendation_state(state)+ logger.info("[ProactiveEngine] delivered '%s' (type=%s, urgency=%.2f, session=%s)",+ decision.target, decision.type, decision.urgency,+ target_session.session_id[:20])++ triggered = await _trigger_main_agent(session_id=target_session.session_id,channel_id=target_channel,decision=decision,trigger_callback=self._trigger_main_agent_callback,+ on_delivered=_on_delivered,)- if not delivered:- logger.info("[ProactiveEngine] not delivered (session busy or trigger failed), skipping")+ if not triggered:+ logger.info("[ProactiveEngine] not triggered (session busy, duplicate inflight, "+ "or trigger failed), skipping")self._last_tick_at = time.time()return False- # ── Step 7: Update state ────────────────────────────────- _increment_daily_count()- _mark_recommended(decision.target, state)- state.add_recommendation({- "type": decision.type,- "target": decision.target,- "reason": decision.reason,- "urgency": decision.urgency,- "tick_at": time.time(),- "session_id": target_session.session_id,- })- state.touch()-- save_recommendation_state(state)+ # 已 fire-and-forget 触发:立即返回,后台跑完会回调 _on_delivered 做计数。+ # cron 端不等主 agent,秒回不超时;_last_tick_at 立即更新让下次 tick 排程正常。self._last_tick_at = time.time()-- logger.info("[ProactiveEngine] delivered '%s' (type=%s, urgency=%.2f, session=%s)",- decision.target, decision.type, decision.urgency,- target_session.session_id[:20])return True# ── Maintenance helpers (called by Cron or manually) ─────────@@ -350,7 +358,6 @@ class ProactiveEngine:from jiuwenswarm.agents.harness.common.recommendation.proactive_actions import (_prune_daily_counts,_prune_cooldown_records,- _prune_limit_notif,)from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (load_recommendation_state,@@ -358,7 +365,6 @@ class ProactiveEngine:)_prune_daily_counts()- _prune_limit_notif()state = load_recommendation_state()_prune_cooldown_records(state)save_recommendation_state(state)diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex d0984d3e2e..77a20a9088 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -245,6 +245,8 @@ function AppContent() {const [saveToastVisible, setSaveToastVisible] = useState(false);// 配置被其他窗口更新后,本窗口若正编辑草稿则弹覆盖确认;无草稿则静默 fetchConfig。const [configChangedConfirmOpen, setConfigChangedConfirmOpen] = useState(false);+ const [proactiveToastVisible, setProactiveToastVisible] = useState(false);+ const [proactiveToastMessage, setProactiveToastMessage] = useState('');const [heartbeatModalOpen, setHeartbeatModalOpen] = useState(false);const [securityAlertVisible, setSecurityAlertVisible] = useState(false);const [securityAlertContent, setSecurityAlertContent] = useState('');@@ -283,6 +285,7 @@ function AppContent() {const saveToastTimerRef = useRef<number | null>(null);/** ConfigPanel 草稿是否有未保存改动(由 onHasChangesChange 上报);config.changed 广播到达时判断是否覆盖草稿。 */const hasChangesRef = useRef(false);+ const proactiveToastTimerRef = useRef<number | null>(null);const lastHeartbeatToastKeyRef = useRef<string | null>(null);/** 自「恢复会话」加载 history 后的分页元数据;用于聊天区顶部加载更早消息 */const [historyPagerMeta, setHistoryPagerMeta] = useState<{@@ -382,6 +385,8 @@ function AppContent() {useEffect(() => () => disposeInFlightHistoryHandles(), [disposeInFlightHistoryHandles]);const { todos, clearTodos } = useTodoStore();const { extensionReady, reset: resetHarnessStore } = useHarnessStore();+ const proactiveNotificationMessage = useHarnessStore((s) => s.proactiveNotificationMessage);+ const setProactiveNotification = useHarnessStore((s) => s.setProactiveNotification);const toolPanelHasContent = useMemo(() => {const hasMessages = messages.length > 0;@@ -561,6 +566,13 @@ function AppContent() {}}, []);+ const clearProactiveToastTimer = useCallback(() => {+ if (proactiveToastTimerRef.current != null) {+ window.clearTimeout(proactiveToastTimerRef.current);+ proactiveToastTimerRef.current = null;+ }+ }, []);+const showSaveToast = useCallback(() => {setSaveToastVisible(true);clearSaveToastTimer();@@ -837,6 +849,24 @@ function AppContent() {}, 15000);}, [clearHeartbeatToastTimer, heartbeatMessage, heartbeatUpdatedAt]);+ // 主动推荐上限提醒:后端推送 source=proactive_notification 的 chat.final 帧+ // 被 useWebSocket 拦截后写入 useHarnessStore.proactiveNotificationMessage;+ // 此处订阅并显示全局 fixed toast(任何面板都可见),8 秒后自动消失。+ useEffect(() => {+ const normalized = proactiveNotificationMessage?.trim();+ if (!normalized) {+ return;+ }+ setProactiveToastMessage(normalized);+ setProactiveToastVisible(true);+ clearProactiveToastTimer();+ proactiveToastTimerRef.current = window.setTimeout(() => {+ setProactiveToastVisible(false);+ setProactiveNotification(null);+ proactiveToastTimerRef.current = null;+ }, 8000);+ }, [clearProactiveToastTimer, proactiveNotificationMessage, setProactiveNotification]);+useEffect(() => {if (!isConnected || initialDataLoaded) {return;@@ -1761,6 +1791,15 @@ function AppContent() {</div>)}+ {/* 主动推荐上限提醒(全局 fixed toast,任何面板都可见) */}+ {proactiveToastVisible && proactiveToastMessage && (+ <div className="app-toast-wrapper app-toast-wrapper--top-center" data-testid="proactive-notification-toast">+ <div className="bg-amber-500 text-white px-4 py-2 rounded-lg shadow-lg animate-rise text-sm">+ {proactiveToastMessage}+ </div>+ </div>+ )}+{/* 安全警告提示 */}{securityAlertVisible && (<div className="app-toast-wrapper app-toast-wrapper--top">diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex ad2d63ee29..90d9ce8e18 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -1690,6 +1690,18 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const currentMode = useSessionStore.getState().mode;const content = normalizeFinalContent(payload);+ // 上限提醒(source=proactive_notification):不进会话历史,改走全局弹窗。+ // 后端每次命中每日上限都推一次,前端用 store 信号驱动 banner 显示 + 定时消失。+ // 必须在 team 模式消息处理之前拦截,否则 team 模式下会被当成 team leader+ // 系统消息进会话历史(与"从会话改到弹窗"的设计意图相反)。+ const source = typeof payload.source === 'string' ? payload.source : '';+ if (source === 'proactive_notification') {+ if (content) {+ useHarnessStore.getState().setProactiveNotification(content);+ }+ return;+ }+// team 模式下,过滤成员输出,只保留外层 leader 回复。if (isHiddenTeamTeammateMessagePayload(currentMode, payload)) {const memberId = getTeamPayloadMemberName(payload);@@ -1754,8 +1766,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const payloadSessionId =typeof payload.session_id === 'string' ? payload.session_id.trim() : '';- // 检查是否为主动推荐消息- const source = typeof payload.source === 'string' ? payload.source : '';+ // 检查是否为主动推荐消息(source 已在 team 处理前提取)const isProactiveRecommendation = source === 'proactive_recommendation';const proactiveType = typeof payload.proactive_type === 'string' ? payload.proactive_type : '';diff --git a/jiuwenswarm/channels/web/frontend/src/stores/harnessStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/harnessStore.tsindex 28a60ab16c..06f591618f 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/harnessStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/harnessStore.ts@@ -119,6 +119,11 @@ interface HarnessState {// Activate interaction pending stateactivateInteraction: ActivateInteractionState | null;+ // Proactive notification message (e.g. "今日主动推荐已达每日上限...")+ // 由后端推送 source=proactive_notification 的 chat.final 帧触发;+ // 前端拦截后不走会话气泡,改走 ChatPanel 顶部弹窗。非空即显示。+ proactiveNotificationMessage: string | null;+// Package list from backendpackages: PackageInfo[];// Native version info@@ -156,6 +161,7 @@ interface HarnessState {messages?: string[];}) => void;setActivateInteraction: (state: ActivateInteractionState | null) => void;+ setProactiveNotification: (message: string | null) => void;reset: () => void;setPackages: (packages: PackageInfo[], nativeVersion: NativeVersionInfo, activeIds: string[]) => void;@@ -242,6 +248,7 @@ export const useHarnessStore = create<HarnessState>((set, get) => ({extensionOrder: [],extensionsByName: {},activateInteraction: null,+ proactiveNotificationMessage: null,packages: [],nativeVersion: null,@@ -457,6 +464,10 @@ export const useHarnessStore = create<HarnessState>((set, get) => ({});},+ setProactiveNotification: (message) => {+ set({ proactiveNotificationMessage: message });+ },+reset: () => {set({stageDefinitions: [],@@ -471,6 +482,7 @@ export const useHarnessStore = create<HarnessState>((set, get) => ({extensionOrder: [],extensionsByName: {},activateInteraction: null,+ proactiveNotificationMessage: null,packages: [],nativeVersion: null,activePackageIds: [],diff --git a/jiuwenswarm/server/runtime/proactive_adapter.py b/jiuwenswarm/server/runtime/proactive_adapter.pyindex c743ca5263..90aab7106c 100644--- a/jiuwenswarm/server/runtime/proactive_adapter.py+++ b/jiuwenswarm/server/runtime/proactive_adapter.py@@ -12,12 +12,34 @@ app_agentserver 只需调 init_proactive_engine(server, config)。from __future__ import annotations+import asyncioimport loggingimport time+from dataclasses import dataclassfrom typing import Anylogger = logging.getLogger(__name__)+# 后台主 agent 推送任务的 inflight 集合,防止同 session 重复并发触发 stream。+# fire-and-forget 后 cron 可能在一个后台 tick 还没跑完时又来下一次,靠这个+# 标志跳过,避免同 session 并发 process_message_stream(不支持并发)。+_proactive_push_inflight: set[str] = set()+++@dataclass+class ProactiveTriggerRequest:+ """一次主动推荐触发请求的具名参数封装(G.FNM.03:多相关参数具名化)。++ 把 session_id / channel_id / query / decision / on_delivered 这一组"本次推荐请求"+ 相关参数封装到一起,让 trigger_main_agent 的签名从 6 参降到 2 参(server + request)。+ server 作为运行时依赖不入此结构。+ """+ session_id: str+ query: str+ decision: Any+ channel_id: str | None = None+ on_delivered: Any = None+def build_proactive_agent():"""Build the lightweight proactive agent for proactive recommendation decisions.@@ -54,14 +76,32 @@ def build_proactive_agent():return None-async def trigger_main_agent(server, session_id: str, channel_id: str | None,- query: str, decision: Any) -> bool:+async def trigger_main_agent(server, request: ProactiveTriggerRequest) -> bool:"""Drive the main agent to run one round with the directive-style query.避让:目标 session 正在跑 stream 时跳过(同 session 不支持并发 stream)。触发后主 agent 自己生成话术 → 进 context engine → stream 推前端。- Returns True on triggered, False on busy/missing adapter/failure.++ fire-and-forget:主 agent 跑一轮被丢到后台 task,本函数立即返回 True+ (表示"已触发",让调用方 cron 秒回不超时)。``request.on_delivered`` 回调在后台+ task **真正跑完**(主 agent 输出流尽、未抛异常)后才被调用——用于让+ 调用方在"推荐确实送达"时再做计数/状态持久化,避免后台失败却已计数。+ 后台 task 失败时不会调 on_delivered,调用方据此知道本次未真正送达。++ Args:+ server: 运行时依赖(不入 ProactiveTriggerRequest)。+ request: 本次触发请求的具名参数(session_id/channel_id/query/decision/on_delivered)。++ Returns:+ True if the main agent was triggered (后台异步跑), False on busy/missing+ adapter/failure/duplicate-inflight."""+ session_id = request.session_id+ channel_id = request.channel_id+ query = request.query+ decision = request.decision+ on_delivered = request.on_delivered+try:from jiuwenswarm.common.schema.agent import AgentRequestexcept ImportError as exc:@@ -97,7 +137,7 @@ async def trigger_main_agent(server, session_id: str, channel_id: str | None,except Exception as exc:logger.debug("[ProactiveEngine] is_deep_agent_executing_for_session check failed: %s", exc)- request = AgentRequest(+ agent_request = AgentRequest(request_id=f"proactive_{decision.type}_{int(time.time() * 1000)}",channel_id=cid,session_id=session_id,@@ -114,35 +154,66 @@ async def trigger_main_agent(server, session_id: str, channel_id: str | None,},is_stream=True,)- try:- async for chunk in agent.process_message_stream(request):- # chunk 经 server.send_push 推 Gateway。send_push 内部已用- # _current_send_lock 串行化 ws 发送,且 build_server_push_wire 走- # chunk 分支(无 response_kind)正确编码——这里只需带齐 chunk 的- # request_id / payload / is_complete,Gateway 才能按 request_id 路由。- #- # 注入 source/proactive_type:主 agent 的 chunk 是普通对话格式,- # 不带主动推荐标记。前端靠 payload.source==='proactive_recommendation'- # 识别卡片、payload.proactive_type 选颜色,缺这俩会退化成普通白色气泡。- # decision.type 在手上,给每个 chunk 的 payload 补上。- try:- chunk_payload = dict(getattr(chunk, "payload", None) or {})- chunk_payload.setdefault("source", "proactive_recommendation")- chunk_payload.setdefault("proactive_type", decision.type)- chunk_payload.setdefault("proactive_target", decision.target)- await server.send_push({- "request_id": getattr(chunk, "request_id", "") or request.request_id,- "channel_id": cid,- "session_id": session_id,- "payload": chunk_payload,- "is_complete": bool(getattr(chunk, "is_complete", False)),- })- except Exception as exc:- logger.debug("[ProactiveEngine] send_push chunk failed: %s", exc)- return True- except Exception as exc:- logger.warning("[ProactiveEngine] trigger: process_message_stream failed: %s", exc, exc_info=True)++ # fire-and-forget:主 agent 跑一轮 + 流式推前端这一段可能很慢(LLM + 工具调用 ++ # post_run 持久化),如果串行 await 会把调用方(_handle_proactive_tick → cron)一起拖到+ # 600 秒超时。这里把它丢后台 task,立即返回 True(表示"已触发"),让 cron 秒回。+ # 推荐内容本来就走 server.send_push 独立流式推前端,不依赖 cron 的请求-响应通道。+ inflight_key = f"{cid}:{session_id}"+ if inflight_key in _proactive_push_inflight:+ logger.info("[ProactiveEngine] trigger: previous push still running for %s, skipping",+ inflight_key)return False+ _proactive_push_inflight.add(inflight_key)++ async def _push_chunks() -> None:+ """后台消费主 agent 的流式输出并推 Gateway。"""+ delivered = False+ try:+ async for chunk in agent.process_message_stream(agent_request):+ # chunk 经 server.send_push 推 Gateway。send_push 内部已用+ # _current_send_lock 串行化 ws 发送,且 build_server_push_wire 走+ # chunk 分支(无 response_kind)正确编码——这里只需带齐 chunk 的+ # request_id / payload / is_complete,Gateway 才能按 request_id 路由。+ #+ # 注入 source/proactive_type:主 agent 的 chunk 是普通对话格式,+ # 不带主动推荐标记。前端靠 payload.source==='proactive_recommendation'+ # 识别卡片、payload.proactive_type 选颜色,缺这俩会退化成普通白色气泡。+ # decision.type 在手上,给每个 chunk 的 payload 补上。+ try:+ chunk_payload = dict(getattr(chunk, "payload", None) or {})+ chunk_payload.setdefault("source", "proactive_recommendation")+ chunk_payload.setdefault("proactive_type", decision.type)+ chunk_payload.setdefault("proactive_target", decision.target)+ await server.send_push({+ "request_id": getattr(chunk, "request_id", "") or agent_request.request_id,+ "channel_id": cid,+ "session_id": session_id,+ "payload": chunk_payload,+ "is_complete": bool(getattr(chunk, "is_complete", False)),+ })+ except Exception as exc:+ logger.debug("[ProactiveEngine] send_push chunk failed: %s", exc)+ # 循环正常跑完(未抛异常)= 主 agent 输出流尽,推荐确实送达。+ delivered = True+ except Exception as exc:+ logger.warning("[ProactiveEngine] trigger: process_message_stream failed: %s",+ exc, exc_info=True)+ finally:+ _proactive_push_inflight.discard(inflight_key)+ # 只在真正送达时回调,让调用方据此做计数/状态持久化(名实相符)。+ # 后台失败(delivered=False)不回调,调用方下次 tick 仍可重试。+ if delivered and on_delivered is not None:+ try:+ on_delivered()+ except Exception as exc:+ logger.warning("[ProactiveEngine] on_delivered callback failed: %s",+ exc, exc_info=True)++ asyncio.create_task(_push_chunks())+ logger.info("[ProactiveEngine] trigger: fired background push for %s (fire-and-forget)",+ inflight_key)+ return Trueasync def init_proactive_engine(server, config: dict[str, Any] | None = None) -> None:@@ -192,8 +263,17 @@ async def init_proactive_engine(server, config: dict[str, Any] | None = None) -># 触发主 agent 回调:tick 决策后,把决策包成指令式 query 触发主 agent# 跑一轮,主 agent 自己生成话术 → 进 context engine → stream 推前端。- async def _trigger_cb(session_id, channel_id, query, decision):- return await trigger_main_agent(server, session_id, channel_id, query, decision)+ # _trigger_cb 是 _trigger_main_agent 的调用契约(位置参数),这里组装成+ # ProactiveTriggerRequest 再交给 trigger_main_agent。+ async def _trigger_cb(session_id, channel_id, query, decision, on_delivered=None):+ req = ProactiveTriggerRequest(+ session_id=session_id,+ channel_id=channel_id,+ query=query,+ decision=decision,+ on_delivered=on_delivered,+ )+ return await trigger_main_agent(server, req)proactive_engine.set_trigger_main_agent_callback(_trigger_cb)server.set_proactive_engine(proactive_engine)diff --git a/tests/symphony/test_proactive_recommendation_flow.py b/tests/symphony/test_proactive_recommendation_flow.pyindex f34769b03c..1c018ac949 100644--- a/tests/symphony/test_proactive_recommendation_flow.py+++ b/tests/symphony/test_proactive_recommendation_flow.py@@ -90,13 +90,22 @@ def _make_proactive_agent(tick_responses: list[dict]):# Capture _trigger_main_agent calls (session_id, channel_id, query, decision)def _capture_trigger(triggered_list):- async def _trigger(session_id, channel_id, query, decision):+ async def _trigger(session_id, channel_id, query, decision, on_delivered=None):triggered_list.append({"session_id": session_id,"channel_id": channel_id,"query": query,"decision": decision,})+ # 真实 trigger_main_agent 是 fire-and-forget:主 agent 跑完才回调 on_delivered+ # 做 Step 7(计数 + save_recommendation_state)。测试 mock 这里同步模拟"后台送达",+ # 立即回调,让 history/count 断言能验证 Step 7 逻辑。+ if on_delivered is not None:+ try:+ on_delivered()+ except Exception:+ # 测试只关心触发与 history,回调异常不掩盖触发本身+ passreturn Truereturn _trigger@@ -355,9 +364,9 @@ async def test_skip_when_main_agent_busy():triggered = []- async def _busy_trigger(session_id, channel_id, query, decision):+ async def _busy_trigger(session_id, channel_id, query, decision, on_delivered=None):triggered.append((session_id, channel_id, decision))- return False # session 正忙+ return False # session 正忙(不触发,on_delivered 不该被调)with tempfile.TemporaryDirectory() as ws:ws_path = Path(ws)@@ -440,7 +449,11 @@ def _capture_notifications(notified_list):@pytest.mark.asyncioasync def test_daily_limit_pushes_notification_once():- """达到每日上限时,应推送一次"已达上限"通知;同日再次 tick 不再刷屏。"""+ """达到每日上限时,每次 tick 命中上限都推送一次"已达上限"通知。++ 旧实现按天去重(每天最多推一次);新行为改为前端弹窗 + 每次命中都推,+ 故同日多次命中上限会多次推送(去重交由前端 toast 的自动消失处理)。+ """notified = []with tempfile.TemporaryDirectory() as ws:@@ -464,10 +477,10 @@ async def test_daily_limit_pushes_notification_once():assert "已达每日上限" in notified[0]["text"]assert "1 条" in notified[0]["text"]- # 第二次 tick:同日已达上限 → 不再刷屏+ # 第二次 tick:同日仍命中上限 → 再次推送(每次命中都推,前端弹窗负责消失)pushed2 = await engine.tick_now()assert pushed2 is False- assert len(notified) == 1, f"同日不应重复推送,实际累计 {len(notified)} 次"+ assert len(notified) == 2, f"同日再次命中上限应再次推送,实际累计 {len(notified)} 次"@pytest.mark.asyncio