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
Enhance A2A history management by introducing source_user_id tracking and related filters. Added user identity checks in outbound dispatch methods and updated database schema to support user ownership. Implemented migration for legacy data and added tests to ensure proper functionality and compliance with enterprise requirements.
NickFuryXXXcb79ffcde4c5
diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsxindex f8e1ddf817..3141e714d5 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'import { useTranslation } from 'react-i18next';import { Check, Copy, Power, RefreshCw, RotateCw, X } from 'lucide-react';import { isEnterprise } from '../../edition';+import { RUNTIME_SCOPE_CHANGED_EVENT } from '../../services/runtimeScope';import type { WebError } from '../../types/websocket';import { A2AOutboundPanel } from './A2AOutboundPanel';import { A2AIngressSecurityFields } from './A2AIngressSecurityFields';@@ -70,8 +71,28 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)const savedCredentialRef = useRef('');const historyResponseGenerationRef = useRef(0);const outboundHistoryResponseGenerationRef = useRef(0);+ const awaitingHistoryReconnectRef = useRef(false);const copyFeedbackTimerRef = useRef<number | null>(null);+ useEffect(() => {+ if (isConnected) awaitingHistoryReconnectRef.current = false;+ }, [isConnected]);++ useEffect(() => {+ if (!enterpriseMode) return;+ const clearUserHistory = () => {+ awaitingHistoryReconnectRef.current = true;+ ++outboundHistoryResponseGenerationRef.current;+ setOutboundHistory([]);+ setOutboundHistoryError(null);+ setOutboundHistoryLoading(false);+ setCopiedHistoryCell(null);+ setCopyError(null);+ };+ window.addEventListener(RUNTIME_SCOPE_CHANGED_EVENT, clearUserHistory);+ return () => window.removeEventListener(RUNTIME_SCOPE_CHANGED_EVENT, clearUserHistory);+ }, [enterpriseMode]);+const acceptSnapshot = useCallback((payload: unknown, credential?: string) => {const next = normalizeA2AIngressSnapshot(payload);@@ -140,7 +161,7 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)const refreshOutboundHistory = useCallback(async (showLoading = true) => {- if (!isConnected) return;+ if (!isConnected || awaitingHistoryReconnectRef.current) return;const responseGeneration = ++outboundHistoryResponseGenerationRef.current;if (showLoading) setOutboundHistoryLoading(true);try {diff --git a/jiuwenswarm/gateway/a2a_manager/manager.py b/jiuwenswarm/gateway/a2a_manager/manager.pyindex 9717c329df..4165f98c1f 100644--- a/jiuwenswarm/gateway/a2a_manager/manager.py+++ b/jiuwenswarm/gateway/a2a_manager/manager.py@@ -222,7 +222,9 @@ class A2AManager:*,source_session_id: str | None = None,source_resource_id: str | None = None,+ source_user_id: str | None = None,) -> dict[str, Any]:+ source_user_id = self._history_user_id(source_user_id)if is_enterprise() and not str(source_resource_id or "").strip():raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)if source_resource_id is not None:@@ -230,11 +232,25 @@ class A2AManager:dispatch_id,source_session_id=str(source_session_id or ""),source_resource_id=source_resource_id,+ source_user_id=source_user_id,)return await self._require_outbound().get_dispatch(dispatch_id)- async def outbound_dispatch_list(self, *, limit: int = 200) -> dict[str, Any]:- return await self._require_outbound().list_dispatches(limit=limit)+ @staticmethod+ def _history_user_id(user_id: str | None) -> str | None:+ if not is_enterprise():+ return None+ normalized = str(user_id or "").strip()+ if not normalized:+ raise A2AOutboundError(A2AOutboundErrorCode.USER_IDENTITY_REQUIRED)+ return normalized++ async def outbound_dispatch_list(+ self, *, limit: int = 200, source_user_id: str | None = None+ ) -> dict[str, Any]:+ return await self._require_outbound().list_dispatches(+ limit=limit, source_user_id=self._history_user_id(source_user_id)+ )async def outbound_find_agents(self,@@ -260,8 +276,10 @@ class A2AManager:mode: str,source_session_id: str,source_resource_id: str | None = None,+ source_user_id: str | None = None,reason: str | None = None,) -> dict[str, Any]:+ source_user_id = self._history_user_id(source_user_id)await self._require_a2a_agent_authorized(source_resource_id, agent_id)return await self._require_outbound_dispatcher().dispatch(agent_id=agent_id,@@ -269,6 +287,7 @@ class A2AManager:mode=mode,source_session_id=source_session_id,source_resource_id=source_resource_id,+ source_user_id=source_user_id,reason=reason,)@@ -278,13 +297,16 @@ class A2AManager:dispatch_id: str,source_session_id: str,source_resource_id: str | None = None,+ source_user_id: str | None = None,) -> dict[str, Any]:+ source_user_id = self._history_user_id(source_user_id)if is_enterprise() and not str(source_resource_id or "").strip():raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)return await self._require_outbound_dispatcher().query_dispatch(dispatch_id,source_session_id=source_session_id,source_resource_id=source_resource_id,+ source_user_id=source_user_id,)async def _resolve_effective_a2a_agent_ids(diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.pyindex 32d03e2262..5bf8f36cc0 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py@@ -276,8 +276,12 @@ class A2AOutboundDispatcher:mode: A2AOutboundDispatchMode | str,source_session_id: str,source_resource_id: str | None = None,+ source_user_id: str | None = None,reason: str | None = None,) -> dict[str, Any]:+ source_user_id = str(source_user_id or "").strip() or None+ if getattr(self._repository, "manager_owned", False) and not source_user_id:+ raise A2AOutboundError(A2AOutboundErrorCode.USER_IDENTITY_REQUIRED)reason_present = bool(str(reason or "").strip())task_text = str(task or "")if not task_text.strip() or len(task_text) > MAX_TASK_TEXT_LENGTH:@@ -304,6 +308,7 @@ class A2AOutboundDispatcher:request_message_id=message_id,source_session_id=session_id,source_resource_id=str(source_resource_id or "").strip() or None,+ source_user_id=source_user_id,created_at=stamp,updated_at=stamp,agent_name=agent.display_name,@@ -366,11 +371,12 @@ class A2AOutboundDispatcher:*,source_session_id: str,source_resource_id: str | None = None,+ source_user_id: str | None = None,) -> dict[str, Any]:normalized_id = str(dispatch_id or "").strip()async with self._query_locks.hold(normalized_id):current = await self._require_owned_dispatch(- normalized_id, source_session_id, source_resource_id+ normalized_id, source_session_id, source_resource_id, source_user_id)if current.is_terminal or not current.remote_task_id:return self._public_dispatch(current)@@ -421,10 +427,11 @@ class A2AOutboundDispatcher:*,source_session_id: str,source_resource_id: str | None = None,+ source_user_id: str | None = None,) -> dict[str, Any]:async with self._query_locks.hold(str(dispatch_id)):current = await self._require_owned_dispatch(- dispatch_id, source_session_id, source_resource_id+ dispatch_id, source_session_id, source_resource_id, source_user_id)if current.is_terminal or not current.remote_task_id:return self._public_dispatch(current)@@ -839,10 +846,16 @@ class A2AOutboundDispatcher:dispatch_id: str,source_session_id: str,source_resource_id: str | None = None,+ source_user_id: str | None = None,) -> A2AOutboundDispatch:+ expected_user = str(source_user_id or "").strip()+ if getattr(self._repository, "manager_owned", False) and not expected_user:+ raise A2AOutboundError(A2AOutboundErrorCode.USER_IDENTITY_REQUIRED)dispatch = await self._repository.get_dispatch(str(dispatch_id or "").strip())if dispatch is None:raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)+ if expected_user and dispatch.source_user_id != expected_user:+ raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)if dispatch.source_session_id != str(source_session_id or "").strip():# Deliberately indistinguishable from a missing ID.raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py b/jiuwenswarm/gateway/a2a_manager/outbound/errors.pyindex 9439851b9e..088239c4b6 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/errors.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/errors.py@@ -17,6 +17,7 @@ class A2AOutboundErrorCode(str, Enum):AGENT_DISABLED = "A2A_AGENT_DISABLED"AGENT_UNAVAILABLE = "A2A_AGENT_UNAVAILABLE"AGENT_NOT_AUTHORIZED = "A2A_AGENT_NOT_AUTHORIZED"+ USER_IDENTITY_REQUIRED = "A2A_USER_IDENTITY_REQUIRED"AGENT_USER_DISABLED = "A2A_AGENT_USER_DISABLED"AGENT_MANAGER_DISABLED = "A2A_AGENT_MANAGER_DISABLED"AGENT_REVIEW_REQUIRED = "A2A_AGENT_REVIEW_REQUIRED"@@ -35,6 +36,7 @@ class A2AOutboundErrorCode(str, Enum):_SAFE_SUMMARIES: dict[A2AOutboundErrorCode, str] = {+ A2AOutboundErrorCode.USER_IDENTITY_REQUIRED: "无法确认当前用户身份。",A2AOutboundErrorCode.DISCOVERY_URL_INVALID: "发现地址无效。",A2AOutboundErrorCode.DISCOVERY_BLOCKED: "发现地址被安全策略拦截。",A2AOutboundErrorCode.CARD_FETCH_FAILED: "无法获取第三方 Agent Card。",diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/models.py b/jiuwenswarm/gateway/a2a_manager/outbound/models.pyindex d042db09c2..87545a1455 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/models.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/models.py@@ -327,6 +327,7 @@ class A2AOutboundDispatch:updated_at: stragent_name: str | None = Nonesource_resource_id: str | None = None+ source_user_id: str | None = Noneremote_task_id: str | None = Noneremote_context_id: str | None = Noneaccepted_at: str | None = None@@ -386,6 +387,7 @@ class A2AOutboundDispatch:updated_at=str(record.get("updated_at") or ""),agent_name=record.get("agent_name"),source_resource_id=record.get("source_resource_id"),+ source_user_id=record.get("source_user_id"),remote_task_id=record.get("remote_task_id"),remote_context_id=record.get("remote_context_id"),accepted_at=record.get("accepted_at"),diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py b/jiuwenswarm/gateway/a2a_manager/outbound/registry.pyindex 033342b9b0..cdba5baf2f 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py@@ -475,10 +475,16 @@ class A2AOutboundRegistry:raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)return item.to_record()- async def list_dispatches(self, *, limit: int = 200) -> dict[str, Any]:+ async def list_dispatches(+ self, *, limit: int = 200, source_user_id: str | None = None+ ) -> dict[str, Any]:normalized_limit = max(1, min(int(limit), 200))- records = await self._repository.list_dispatches(limit=normalized_limit)- total = await self._repository.count_dispatches()+ if getattr(self._repository, "manager_owned", False) and not source_user_id:+ raise A2AOutboundError(A2AOutboundErrorCode.USER_IDENTITY_REQUIRED)+ records = await self._repository.list_dispatches(+ limit=normalized_limit, source_user_id=source_user_id+ )+ total = await self._repository.count_dispatches(source_user_id=source_user_id)items = []for item in records:items.append(diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py b/jiuwenswarm/gateway/a2a_manager/outbound/repository.pyindex a843d48800..82d2bf48fb 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/repository.py@@ -217,21 +217,29 @@ class A2AOutboundRepository:*,limit: int | None = None,offset: int = 0,+ source_user_id: str | None = None,) -> list[A2AOutboundDispatch]:rows = await self._store.list(A2A_OUTBOUND_DISPATCH_STORE_NAME,- filters=self._codec.list_filters(),+ filters=self._dispatch_filters(source_user_id),order_by="created_at DESC",limit=None if limit is None else max(0, int(limit)),offset=max(0, int(offset)),)return [self._codec.dispatch_from_record(row) for row in rows]- async def count_dispatches(self) -> int:+ def _dispatch_filters(self, source_user_id: str | None) -> dict[str, Any]:+ # None is reserved for system-wide maintenance and personal history.+ filters = dict(self._codec.list_filters() or {})+ if source_user_id is not None:+ filters["source_user_id"] = source_user_id+ return filters++ async def count_dispatches(self, *, source_user_id: str | None = None) -> int:"""Return the total matching record count, skipping row decoding."""rows = await self._store.list(A2A_OUTBOUND_DISPATCH_STORE_NAME,- filters=self._codec.list_filters(),+ filters=self._dispatch_filters(source_user_id),)return len(rows)diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex ce561dd42a..88843c6006 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -2061,12 +2061,13 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:ws, req_id, lambda: a2a_manager.outbound_delete(str(params.get("agent_id") or "")))- async def _a2a_outbound_dispatch_get(ws, req_id, params, session_id):+ async def _a2a_outbound_dispatch_get(ws, req_id, params, session_id, user_id=None):await _send_a2a_outbound(ws,req_id,lambda: a2a_manager.outbound_dispatch_get(str(params.get("dispatch_id") or ""),+ source_user_id=user_id,source_session_id=(session_id if is_enterprise() else None),source_resource_id=(str(params.get("bot_id") or "") if is_enterprise() else None@@ -2074,7 +2075,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:),)- async def _a2a_outbound_dispatch_list(ws, req_id, params, session_id):+ async def _a2a_outbound_dispatch_list(ws, req_id, params, session_id, user_id=None):try:limit = int(params.get("limit", 200))except (TypeError, ValueError):@@ -2090,7 +2091,9 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:await _send_a2a_outbound(ws,req_id,- lambda: a2a_manager.outbound_dispatch_list(limit=limit),+ lambda: a2a_manager.outbound_dispatch_list(+ limit=limit, source_user_id=user_id+ ),)channel.register_method("a2a.outbound.settings.get", _a2a_outbound_settings_get)diff --git a/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py b/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.pynew file mode 100644index 0000000000..f38e503ff7--- /dev/null+++ b/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py@@ -0,0 +1,44 @@+"""Upgrade only A2A history ownership; legacy rows remain unowned."""++from sqlalchemy import inspect, text+from sqlalchemy.exc import DBAPIError+from sqlalchemy.ext.asyncio import AsyncEngine++from .a2a_models import A2A_OUTBOUND_DISPATCH_TABLE_DEF+++async def ensure_dispatch_user_column(engine: AsyncEngine) -> None:+ """Add the nullable owner before init_table creates its declared index."""+ table_name = A2A_OUTBOUND_DISPATCH_TABLE_DEF.table_name+ column = next(+ col+ for col in A2A_OUTBOUND_DISPATCH_TABLE_DEF.columns+ if col.name == "source_user_id"+ )++ def has_owner(connection):+ inspector = inspect(connection)+ return inspector.has_table(table_name) and any(+ col["name"] == column.name for col in inspector.get_columns(table_name)+ )++ def upgrade(connection):+ if not inspect(connection).has_table(table_name) or has_owner(connection):+ return+ quote = connection.dialect.identifier_preparer.quote+ connection.execute(+ text(+ f"ALTER TABLE {quote(table_name)} ADD COLUMN "+ f"{quote(column.name)} VARCHAR({column.length}) NULL"+ )+ )++ try:+ async with engine.begin() as connection:+ await connection.run_sync(upgrade)+ except DBAPIError:+ # Another Gateway may have added it concurrently. Verify after rollback;+ # all other failures must prevent startup with a partially upgraded table.+ async with engine.connect() as connection:+ if not await connection.run_sync(has_owner):+ raisediff --git a/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py b/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.pyindex f361c1be73..3d30565845 100644--- a/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py+++ b/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py@@ -56,6 +56,7 @@ A2A_OUTBOUND_DISPATCH_TABLE_DEF = TableDefinition(ColumnDefinition("request_message_id", "string", length=100, nullable=False),ColumnDefinition("source_session_id", "string", length=512, nullable=False),ColumnDefinition("source_resource_id", "string", length=100, nullable=True),+ ColumnDefinition("source_user_id", "string", length=64, nullable=True),ColumnDefinition("remote_task_id", "string", length=256, nullable=True),ColumnDefinition("remote_context_id", "string", length=256, nullable=True),ColumnDefinition("accepted_at", "datetime", nullable=True),@@ -73,6 +74,7 @@ A2A_OUTBOUND_DISPATCH_TABLE_DEF = TableDefinition(indexes=[IndexDefinition(["dispatch_id"], unique=True),IndexDefinition(["source_session_id"]),+ IndexDefinition(["source_user_id", "created_at"]),IndexDefinition(["source_resource_id"]),IndexDefinition(["created_at"]),],diff --git a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py b/jiuwenswarm/gateway/config/enterprise/tables/table_init.pyindex 9ffc12b2d9..99a07119e1 100644--- a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py+++ b/jiuwenswarm/gateway/config/enterprise/tables/table_init.py@@ -13,6 +13,7 @@ from .a2a_models import (A2A_OUTBOUND_RUNTIME_STATE_TABLE_DEF,A2A_OUTBOUND_USER_STATE_TABLE_DEF,)+from .a2a_migration import ensure_dispatch_user_columnfrom .application_config_models import (LOG_MASKING_RULE_TABLE_DEF,LOGGING_CONFIG_TABLE_DEF,@@ -68,4 +69,6 @@ ALL_TABLE_DEFINITIONS: tuple[TableDefinition, ...] = (async def init_all_tables(handler: DBHandler) -> None:"""对已连接的 ``handler`` 依次 ``init_table``,幂等(表已存在则跳过创建逻辑)。"""for table_def in ALL_TABLE_DEFINITIONS:+ if table_def is A2A_OUTBOUND_DISPATCH_TABLE_DEF:+ await ensure_dispatch_user_column(handler.get_engine())await handler.init_table(table_def)diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex 1f3c7ab1f5..15f372a978 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -228,7 +228,7 @@ class MessageHandler(FileTransferMixin, ABC):self._running = Falseself._a2a_outbound_tool_manager: Any | None = Noneself._active_a2a_outbound_tool_tasks: dict[- str, tuple[asyncio.Task[Any], str, str]+ str, tuple[asyncio.Task[Any], str, str, str]] = {}self._forward_task: asyncio.Task | None = Noneself._stream_tasks: dict[str, asyncio.Task] = {} # request_id -> task@@ -3085,6 +3085,7 @@ class MessageHandler(FileTransferMixin, ABC):current_task = asyncio.current_task()trusted_session_id = str(session_id or "").strip()source_resource_id = ""+ source_user_id = ""resource_identity_invalid = Falseif is_enterprise():from jiuwenswarm.common.request_identity import web_routing_identity@@ -3105,6 +3106,7 @@ class MessageHandler(FileTransferMixin, ABC):if identities and all(item == identities[0] for item in identities):source_identity = identities[0]source_resource_id = str(source_identity.get("bot_id") or "").strip()+ source_user_id = str(source_identity.get("user_id") or "").strip()requested_resource_id = str(params.get("resource_id") or "").strip()missing_source = not source_resource_idif method == A2A_TOOL_CANCEL_CALL:@@ -3133,6 +3135,8 @@ class MessageHandler(FileTransferMixin, ABC):and not resource_identity_invalidand active[1] == trusted_session_idand active[2] == source_resource_id+ and active[3] == source_user_id+ and (not is_enterprise() or bool(source_user_id))and target is not current_task)if canceled:@@ -3155,10 +3159,13 @@ class MessageHandler(FileTransferMixin, ABC):current_task,trusted_session_id,source_resource_id,+ source_user_id,)try:if resource_identity_invalid:raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)+ if is_enterprise() and method != A2A_TOOL_FIND_AGENTS and not source_user_id:+ raise A2AOutboundError(A2AOutboundErrorCode.USER_IDENTITY_REQUIRED)if manager is None:raise A2AOutboundError(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)source_session_id = trusted_session_id@@ -3186,6 +3193,8 @@ class MessageHandler(FileTransferMixin, ABC):}if source_resource_id:call_params["source_resource_id"] = source_resource_id+ if source_user_id:+ call_params["source_user_id"] = source_user_idresult = await manager.outbound_dispatch_task(**call_params)elif method == A2A_TOOL_GET_DISPATCH:call_params = {@@ -3194,6 +3203,8 @@ class MessageHandler(FileTransferMixin, ABC):}if source_resource_id:call_params["source_resource_id"] = source_resource_id+ if source_user_id:+ call_params["source_user_id"] = source_user_idresult = await manager.outbound_get_dispatch(**call_params)response = {"jsonrpc": "2.0", "id": jsonrpc_id, "result": result}except A2AOutboundError as exc:diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.pyindex 425907e51c..17a205f8b9 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/routers/template_routers.py@@ -8,6 +8,9 @@ from typing import Anyfrom fastapi import APIRouter, HTTPException, Request+from jiuwenswarm.gateway.a2a_manager.outbound.discovery import A2AOutboundDiscoveryService+from jiuwenswarm.gateway.a2a_manager.outbound.errors import A2AOutboundError+from ..core.template.a2a_access_policy_template import A2AAccessPolicyTemplateServicefrom ..core.template.a2a_outbound_template import A2AOutboundTemplateServicefrom ..core.template.agent_template import AgentTemplateService@@ -53,7 +56,7 @@ def _http_exc(exc: ValueError) -> HTTPException:return HTTPException(status_code=status, detail=detail)-def _require_secure_a2a_credential_transport(+async def _require_secure_a2a_credential_transport(request: Request,tag: str,business: dict[str, Any],@@ -62,11 +65,20 @@ def _require_secure_a2a_credential_transport(# G.CTL.03: if 内布尔条件不超过 3 个,isinstance 判断前置if tag != "a2a_outbound" or not isinstance(credential, dict):return- if credential.get("operation") == "replace" and request.url.scheme.lower() != "https":+ if credential.get("operation") != "replace":+ return+ data = business.get("data") or {}+ policy = data.get("network_policy") if isinstance(data, dict) else None+ policy = policy if isinstance(policy, dict) else {}+ try:+ await A2AOutboundDiscoveryService().validate_network_target(+ str(request.url), network_policy=policy,+ )+ except A2AOutboundError as exc:raise HTTPException(status_code=400,- detail="A2A credentials may only be synchronized over HTTPS",- )+ detail="A2A credential sync blocked by network access settings",+ ) from excdef _add_template_crud(@@ -84,7 +96,7 @@ def _add_template_crud(body: Any,):sync = await build_sync_context(body, request.method)- _require_secure_a2a_credential_transport(request, tag, sync.business)+ await _require_secure_a2a_credential_transport(request, tag, sync.business)try:result = await svc_factory().create(sync.business@@ -102,7 +114,7 @@ def _add_template_crud(body: Any,):sync = await build_sync_context(body, request.method)- _require_secure_a2a_credential_transport(request, tag, sync.business)+ await _require_secure_a2a_credential_transport(request, tag, sync.business)try:await svc_factory().update(template_id, sync.businessdiff --git a/tests/unit_tests/gateway/test_a2a_history_migration.py b/tests/unit_tests/gateway/test_a2a_history_migration.pynew file mode 100644index 0000000000..e68e8c62fe--- /dev/null+++ b/tests/unit_tests/gateway/test_a2a_history_migration.py@@ -0,0 +1,119 @@+"""Exercise real SQLite schema upgrades without assigning legacy ownership."""++from dataclasses import replace+from datetime import datetime++import pytest+from sqlalchemy import inspect, text+from openjiuwen_runtime.foundation.db.sqlite_handler import SQLiteHandler++from jiuwenswarm.gateway.config.enterprise.tables.a2a_models import (+ A2A_OUTBOUND_DISPATCH_TABLE_DEF,+)+from jiuwenswarm.gateway.config.enterprise.tables.table_init import init_all_tables+from jiuwenswarm.gateway.config.enterprise.tables import table_init+from jiuwenswarm.gateway.a2a_manager.outbound.registry import A2AOutboundRegistry+from jiuwenswarm.gateway.storage.backends.db.persistent_store import DbPersistentBackend+from jiuwenswarm.gateway.storage_assembly import (+ build_gateway_store_registry,+ create_a2a_outbound_repository,+)+++ "ignore:This declarative base already contains a class:sqlalchemy.exc.SAWarning"+)[email protected]("legacy", [True, False])+async def test_a2a_schema_upgrade_is_idempotent_and_does_not_claim_history(+ tmp_path, monkeypatch, legacy+):+ handler = SQLiteHandler(str(tmp_path / "gateway.db"))+ await handler.connect()+ table = A2A_OUTBOUND_DISPATCH_TABLE_DEF+ monkeypatch.setattr(table_init, "ALL_TABLE_DEFINITIONS", (table,))+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ try:+ if legacy:+ old = replace(+ table,+ columns=[col for col in table.columns if col.name != "source_user_id"],+ indexes=[+ idx for idx in table.indexes if "source_user_id" not in idx.columns+ ],+ )+ await handler.init_table(old)+ await handler.create(+ table.table_name,+ {+ "dispatch_id": "legacy",+ "agent_id": "agent",+ "agent_revision": 1,+ "mode": "async",+ "status": "completed",+ "request_message_id": "request",+ "source_session_id": "session",+ "created_at": datetime(2026, 9, 1),+ "updated_at": datetime(2026, 9, 1),+ },+ )+ await init_all_tables(handler)+ await init_all_tables(handler)+ async with handler.get_engine().connect() as connection:+ columns = await connection.run_sync(+ lambda c: inspect(c).get_columns(table.table_name)+ )+ owner = next(col for col in columns if col["name"] == "source_user_id")+ assert owner["nullable"] is True+ indexes = await connection.run_sync(+ lambda c: inspect(c).get_indexes(table.table_name)+ )+ assert (+ sum(+ idx["column_names"] == ["source_user_id", "created_at"]+ for idx in indexes+ )+ == 1+ )+ if legacy:+ result = await connection.execute(+ text(+ "SELECT source_user_id FROM a2a_outbound_dispatch WHERE dispatch_id='legacy'"+ )+ )+ assert result.one() == (None,)++ # Verify the actual database filter, not just the in-memory backend.+ class Connection:+ async def ensure_ready(self):+ return handler++ store = DbPersistentBackend(Connection(), build_gateway_store_registry())+ repository = create_a2a_outbound_repository(store)+ for name, user, day in [+ ("a1", "alice", 1),+ ("a2", "alice", 2),+ ("b1", "bob", 3),+ ]:+ await handler.create(+ table.table_name,+ {+ "dispatch_id": name,+ "agent_id": "agent",+ "agent_revision": 1,+ "mode": "async",+ "status": "completed",+ "request_message_id": name,+ "source_session_id": "session",+ "source_user_id": user,+ "created_at": datetime(2026, 9, day),+ "updated_at": datetime(2026, 9, day),+ },+ )+ result = await A2AOutboundRegistry(repository).list_dispatches(+ limit=1, source_user_id="alice"+ )+ assert result["total"] == 2+ assert [item["dispatch_id"] for item in result["items"]] == ["a2"]+ finally:+ await handler.disconnect()diff --git a/tests/unit_tests/gateway/test_a2a_manager.py b/tests/unit_tests/gateway/test_a2a_manager.pyindex 4bab5b064e..c08f4a4d08 100644--- a/tests/unit_tests/gateway/test_a2a_manager.py+++ b/tests/unit_tests/gateway/test_a2a_manager.py@@ -976,12 +976,14 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(task="work",mode="sync",source_session_id="session-1",+ source_user_id="user-1",source_resource_id="resource-1",)assert dispatched["source_resource_id"] == "resource-1"queried = await manager.outbound_get_dispatch(dispatch_id="dispatch-1",source_session_id="session-1",+ source_user_id="user-1",source_resource_id="resource-1",)assert queried["source_resource_id"] == "resource-1"@@ -990,6 +992,7 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(await manager.outbound_get_dispatch(dispatch_id="dispatch-1",source_session_id="session-1",+ source_user_id="user-1",source_resource_id="",)assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED@@ -998,6 +1001,7 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(await manager.outbound_dispatch_get("dispatch-1",source_session_id="session-1",+ source_user_id="user-1",source_resource_id=None,)assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED@@ -1008,6 +1012,7 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(task="work",mode="sync",source_session_id="session-1",+ source_user_id="user-1",source_resource_id="resource-1",)assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED@@ -1022,6 +1027,7 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(task="work",mode="sync",source_session_id="session-1",+ source_user_id="user-1",source_resource_id="resource-1",)assert exc_info.value.code is expected_codediff --git a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.pyindex 7327aee4da..a7adabd3f3 100644--- a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py+++ b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py@@ -27,6 +27,100 @@ class _WebChannelProbe:)[email protected]("transport", ["ws", "http"])+async def test_enterprise_history_uses_connection_owner_for_list_and_details(+ monkeypatch, transport+):+ from types import SimpleNamespace+ from jiuwenswarm.gateway.a2a_manager.outbound import (+ A2AOutboundDispatch,+ A2AOutboundDispatchMode,+ A2AOutboundDispatchStatus,+ A2AOutboundDispatcher,+ A2AOutboundRepository,+ )+ from jiuwenswarm.gateway.a2a_manager.outbound.registry import A2AOutboundRegistry+ from jiuwenswarm.gateway.channel_manager.web.web_rpc_host import (+ WebRpcHost,+ MethodHandlerInvocation,+ )+ from jiuwenswarm.gateway.channel_manager.web.web_ws_transport import WebWsTransport+ from jiuwenswarm.gateway.channel_manager.web.outbound import HttpJsonOutbound+ from jiuwenswarm.gateway.storage.backends.memory_persistent import (+ InMemoryPersistentBackend,+ )++ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ repository = A2AOutboundRepository(InMemoryPersistentBackend())+ repository.manager_owned = True+ for owner in ("alice", "bob", None):+ await repository.create_dispatch(+ A2AOutboundDispatch(+ dispatch_id=owner or "legacy",+ agent_id="agent-1",+ agent_revision=1,+ mode=A2AOutboundDispatchMode.ASYNC,+ status=A2AOutboundDispatchStatus.COMPLETED,+ request_message_id="message",+ source_session_id="session",+ source_resource_id="bot",+ source_user_id=owner,+ created_at="2026-09-01T00:00:00Z",+ updated_at="2026-09-01T00:00:00Z",+ )+ )+ manager = object.__new__(A2AManager)+ manager._outbound = A2AOutboundRegistry(repository)+ manager._outbound_dispatcher = A2AOutboundDispatcher(repository)+ channel = _WebChannelProbe()+ channel.ws = WebWsTransport+ host = WebRpcHost(channel)+ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))+ connection = (+ HttpJsonOutbound(headers={}, session_id="session")+ if transport == "http"+ else SimpleNamespace()+ )++ async def invoke(method, user, **params):+ setattr(connection, "_web_connection_user_id", user)+ await host.invoke_method_handler(+ MethodHandlerInvocation(+ ws=connection,+ method=method,+ req_id="test",+ session_id="session",+ params={+ "user_id": "bob",+ "source_user_id": "bob",+ "bot_id": "bot",+ **params,+ },+ handler=channel.methods[method],+ )+ )+ return channel.responses[-1]++ for user in ("alice", "bob"):+ response = await invoke("a2a.outbound.dispatch.list", user)+ assert response["ok"] is True+ assert response["payload"]["total"] == 1+ assert [item["dispatch_id"] for item in response["payload"]["items"]] == [user]+ for dispatch_id in ("bob", "legacy", "missing"):+ response = await invoke(+ "a2a.outbound.dispatch.get", "alice", dispatch_id=dispatch_id+ )+ assert response["ok"] is False+ assert response["code"] == "A2A_DISPATCH_NOT_FOUND"+ assert (await invoke("a2a.outbound.dispatch.get", "alice", dispatch_id="alice"))[+ "ok"+ ] is True+ for method in ("a2a.outbound.dispatch.list", "a2a.outbound.dispatch.get"):+ response = await invoke(method, None, dispatch_id="alice")+ assert response["code"] == "A2A_USER_IDENTITY_REQUIRED"++class _ChannelManagerProbe:def register_channel(self, channel) -> None:return None@@ -86,7 +180,7 @@ class _OutboundRegistryProbe:async def get_dispatch(self, dispatch_id):return {"dispatch_id": dispatch_id}- async def list_dispatches(self, *, limit=200):+ async def list_dispatches(self, *, limit=200, source_user_id=None):return {"items": [], "total": 0, "limit": limit}@@ -427,6 +521,7 @@ async def test_enterprise_dispatch_get_passes_trusted_resource_scope("dispatch-get",{"dispatch_id": "dispatch-1", "bot_id": "resource-1"},"session-1",+ user_id="user-1",)assert calls == [@@ -435,6 +530,7 @@ async def test_enterprise_dispatch_get_passes_trusted_resource_scope({"source_session_id": "session-1","source_resource_id": "resource-1",+ "source_user_id": "user-1",},)]diff --git a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.pyindex 536ce43d7c..e90a7082fa 100644--- a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py+++ b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py@@ -893,6 +893,7 @@ async def test_dispatch_query_is_scoped_to_originating_session() -> None:mode="async",source_session_id="s1",source_resource_id="resource-1",+ source_user_id="user-1",)with pytest.raises(A2AOutboundError) as error:@@ -904,19 +905,127 @@ async def test_dispatch_query_is_scoped_to_originating_session() -> None:repository.manager_owned = Truewith pytest.raises(A2AOutboundError) as error:await dispatcher.query_dispatch(- accepted["dispatch_id"], source_session_id="s1"+ accepted["dispatch_id"], source_session_id="s1", source_user_id="user-1")assert error.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZEDwith pytest.raises(A2AOutboundError) as error:await dispatcher.query_dispatch(accepted["dispatch_id"],- source_session_id="s1",+ source_session_id="s1", source_user_id="user-1",source_resource_id="resource-2",)assert error.value.code is A2AOutboundErrorCode.DISPATCH_NOT_FOUND+async def test_enterprise_dispatch_requires_user_and_hides_other_and_legacy_records():+ client = _FakeClient([_task_event(TaskState.TASK_STATE_SUBMITTED)])+ dispatcher, repository = await _dispatcher(client)+ repository.manager_owned = True+ with pytest.raises(A2AOutboundError) as error:+ await dispatcher.dispatch(+ agent_id="agent-1",+ task="work",+ mode="async",+ source_session_id="s1",+ source_resource_id="r1",+ )+ assert error.value.code is A2AOutboundErrorCode.USER_IDENTITY_REQUIRED+ assert client.sent_requests == []+ assert await repository.count_dispatches() == 0+ accepted = await dispatcher.dispatch(+ agent_id="agent-1",+ task="work",+ mode="async",+ source_session_id="s1",+ source_resource_id="r1",+ source_user_id="alice",+ )+ record = await repository.get_dispatch(accepted["dispatch_id"])+ assert record.source_user_id == "alice"+ await repository.create_dispatch(+ replace(record, dispatch_id="legacy", source_user_id=None)+ )+ await repository.transition_dispatch(+ record.dispatch_id, A2AOutboundDispatchStatus.COMPLETED+ )+ for method in (dispatcher.query_dispatch, dispatcher.cancel_dispatch):+ for dispatch_id, user in [(record.dispatch_id, "bob"), ("legacy", "alice")]:+ with pytest.raises(A2AOutboundError) as error:+ await method(+ dispatch_id,+ source_session_id="s1",+ source_resource_id="r1",+ source_user_id=user,+ )+ assert error.value.code is A2AOutboundErrorCode.DISPATCH_NOT_FOUND+ with pytest.raises(A2AOutboundError) as error:+ await method(+ record.dispatch_id, source_session_id="s1", source_resource_id="r1"+ )+ assert error.value.code is A2AOutboundErrorCode.USER_IDENTITY_REQUIRED+ own = await dispatcher.query_dispatch(+ record.dispatch_id,+ source_session_id="s1",+ source_resource_id="r1",+ source_user_id="alice",+ )+ assert own["dispatch_id"] == record.dispatch_id+ assert client.get_requests == []++[email protected]("method", [A2A_TOOL_DISPATCH_TASK, A2A_TOOL_GET_DISPATCH])[email protected]("fallback", [False, True])+async def test_enterprise_reverse_rpc_uses_context_user_not_tool_params(+ monkeypatch, method, fallback+):+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ calls, replies = [], []++ class Manager:+ async def outbound_dispatch_task(self, **kwargs):+ calls.append(kwargs)+ return {}++ outbound_get_dispatch = outbound_dispatch_task++ handler = object.__new__(MessageHandler)+ handler._a2a_outbound_tool_manager = Manager()+ handler._active_a2a_outbound_tool_tasks = {}++ async def publish(message):+ replies.append(message)++ handler.publish_user_messages = publish+ chunk = SimpleNamespace(+ channel_id="web",+ payload={+ "id": "rpc-user",+ "method": method,+ "params": {"resource_id": "r1", "user_id": "bob", "source_user_id": "bob"},+ },+ )+ metadata = {"user_id": "alice", "routing": {"bot_id": "r1"}}+ handler._stream_sessions = {"active": "s1"}+ handler._stream_channels = {"active": "web"}+ handler._stream_metadata = {"active": metadata}+ await handler._handle_a2a_outbound_tool_push(+ chunk=chunk, session_id="s1", request_metadata=None if fallback else metadata+ )+ assert calls[-1]["source_user_id"] == "alice"+ metadata.pop("user_id")+ await handler._handle_a2a_outbound_tool_push(+ chunk=chunk, session_id="s1", request_metadata=None if fallback else metadata+ )+ assert len(calls) == 1+ assert (+ replies[-1].params["response"]["error"]["data"]["code"]+ == "A2A_USER_IDENTITY_REQUIRED"+ )++class _Backend:ready = True@@ -1894,7 +2003,7 @@ async def test_enterprise_cancel_call_binds_identity_via_active_calls(replies.append(message)handler.publish_user_messages = publish- metadata = {"routing": {"bot_id": "resource-1"}}+ metadata = {"user_id": "user-1", "routing": {"bot_id": "resource-1"}}dispatch_chunk = SimpleNamespace(payload={"id": "rpc-dispatch",diff --git a/tests/unit_tests/gateway/test_a2a_outbound_repository.py b/tests/unit_tests/gateway/test_a2a_outbound_repository.pyindex a79b828ea0..bbd7b6b643 100644--- a/tests/unit_tests/gateway/test_a2a_outbound_repository.py+++ b/tests/unit_tests/gateway/test_a2a_outbound_repository.py@@ -112,6 +112,44 @@ class _SecretProbe:self.values.pop(key, None)+async def test_history_filters_owner_before_limit_and_preserves_legacy_and_cleanup():+ from jiuwenswarm.gateway.a2a_manager.outbound.registry import A2AOutboundRegistry++ store = InMemoryPersistentBackend()+ repository = A2AOutboundRepository(store)+ repository.manager_owned = True+ legacy = _dispatch("legacy", status=A2AOutboundDispatchStatus.COMPLETED).to_record()+ legacy.pop("source_user_id")+ await store.create("a2a_outbound_dispatch", legacy)+ for name, owner, day in [("a1", "alice", 1), ("a2", "alice", 2), ("b1", "bob", 3)]:+ await repository.create_dispatch(+ replace(_dispatch(name, created_at=_stamp(day)), source_user_id=owner)+ )+ await repository.transition_dispatch(name, A2AOutboundDispatchStatus.COMPLETED)+ registry = A2AOutboundRegistry(repository)+ result = await registry.list_dispatches(limit=1, source_user_id="alice")+ assert [item["dispatch_id"] for item in result["items"]] == ["a2"]+ assert result["total"] == 2+ result = await registry.list_dispatches(source_user_id="bob")+ assert [item["dispatch_id"] for item in result["items"]] == ["b1"]+ assert result["total"] == 1+ assert await registry.list_dispatches(source_user_id="nobody") == {+ "items": [],+ "total": 0,+ }+ with pytest.raises(A2AOutboundError) as error:+ await registry.list_dispatches()+ assert error.value.code is A2AOutboundErrorCode.USER_IDENTITY_REQUIRED+ assert (await repository.get_dispatch("legacy")).source_user_id is None+ assert (await repository.get_dispatch("a1")).source_user_id == "alice"+ with pytest.raises(ValueError):+ await repository.transition_dispatch("a1", "completed", source_user_id="bob")+ assert await repository.count_dispatches() == 4+ assert await repository.cleanup_dispatches(max_records=1, max_age_days=0) == 3+ assert [item.dispatch_id for item in await repository.list_dispatches()] == ["b1"]++@pytest.mark.asyncioasync def test_agent_roundtrip_redacts_card_secrets_and_hides_credential_ref() -> None:store = InMemoryPersistentBackend()diff --git a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.pyindex 0de74cb7f5..9ded0c991d 100644--- a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py+++ b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py@@ -186,7 +186,17 @@ def _projection_record() -> dict[str, Any]:@pytest.fixture-def a2a_receiver() -> Iterator[tuple[TestClient, dict[str, Any], _Secrets]]:+def a2a_receiver(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[TestClient, dict[str, Any], _Secrets]]:+ from jiuwenswarm.gateway.a2a_manager.outbound.discovery import A2AOutboundDiscoveryService++ async def resolve(host, _port):+ return ["8.8.8.8" if host == "gateway.test" else host]++ routers = import_manager_config_receiver_module("routers.template_routers")+ monkeypatch.setattr(+ routers, "A2AOutboundDiscoveryService",+ lambda: A2AOutboundDiscoveryService(address_resolver=resolve),+ )store = InMemoryPersistentBackend()repos = create_enterprise_record_repositories(store)set_enterprise_record_repositories(repos)@@ -730,6 +740,7 @@ async def test_enterprise_dispatch_updates_shared_runtime_state() -> None:task="weather",mode="sync",source_session_id="session-1",+ source_user_id="user-1",)assert result["status"] == A2AOutboundDispatchStatus.COMPLETED.value@@ -762,6 +773,7 @@ async def test_enterprise_dispatch_records_unreachable_runtime_state() -> None:task="weather",mode="sync",source_session_id="session-1",+ source_user_id="user-1",)assert result["status"] == A2AOutboundDispatchStatus.DISPATCH_FAILED.value@@ -988,3 +1000,25 @@ async def test_enterprise_projection_fails_closed_for_invalid_resource_or_policy)assert await projection.resolve_effective_a2a_agent_ids("missing") == frozenset()++[email protected]("host", ["10.0.0.8", "8.8.8.8", "127.0.0.1", "169.254.169.254", "100.64.0.1"])[email protected]("scheme", ["http", "https"])[email protected]("flags", [+ (False, False, False), (True, True, False), (True, False, True),+ (False, True, True), (True, True, True),+])+def test_credential_receiver_network_policy(a2a_receiver, host, scheme, flags):+ _, _, secrets = a2a_receiver+ app_module = import_manager_config_receiver_module("http.app")+ policy = dict(zip(("allow_http", "allow_private_network", "allow_public_http"), flags))+ payload = _outbound_payload()+ payload["data"] = {"network_policy": policy}+ allowed = (+ (host == "8.8.8.8" or (host == "10.0.0.8" and flags[1]))+ and (scheme == "https" or (flags[0] and (host != "8.8.8.8" or flags[2])))+ )+ with TestClient(app_module.create_app(), base_url=f"{scheme}://{host}") as client:+ response = client.post("/api/v1/a2a-outbound-templates", json=payload)+ assert response.status_code == (200 if allowed else 400)+ assert bool(secrets.values) is allowed