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(a2a): isolate outbound user state by source_user_id
NickFuryXXXb0924783cf4a
diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsxindex 687ffbae92..9022cf7f43 100644--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';import { ChevronDown, Plus, Power, RefreshCw, Search, Server, Trash2, X } from 'lucide-react';import { isEnterprise } from '../../edition';+import { RUNTIME_SCOPE_CHANGED_EVENT } from '../../services/runtimeScope';import type { WebError } from '../../types/websocket';import { Switch } from '../Switch';import { A2AOutboundCredentialInput } from './A2AOutboundCredentialInput';@@ -59,6 +60,27 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer} | null>(null);const generationRef = useRef(createA2AOutboundRequestScope());const editGenerationRef = useRef(createA2AOutboundRequestScope());+ const awaitingReconnectRef = useRef(false);+ const userScopeRef = useRef(createA2AOutboundRequestScope());++ useEffect(() => {+ if (isConnected) awaitingReconnectRef.current = false;+ }, [isConnected]);++ useEffect(() => {+ if (!enterpriseMode) return;+ const clearUserState = () => {+ awaitingReconnectRef.current = true;+ userScopeRef.current.next();+ generationRef.current.next();+ setAgents([]);+ setBusy(null);+ setError(null);+ setNotice(null);+ };+ window.addEventListener(RUNTIME_SCOPE_CHANGED_EVENT, clearUserState);+ return () => window.removeEventListener(RUNTIME_SCOPE_CHANGED_EVENT, clearUserState);+ }, [enterpriseMode]);useEffect(() => {editGenerationRef.current.next();@@ -69,7 +91,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer}, [isConnected]);const refresh = useCallback(async () => {- if (!isConnected) return;+ if (!isConnected || awaitingReconnectRef.current) return;const generation = generationRef.current.next();try {const [payload, rawSettings] = enterpriseMode@@ -202,12 +224,13 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainer};const operate = async (agent: A2AOutboundAgent, operation: 'toggle' | 'refresh' | 'confirm' | 'reject' | 'delete') => {- if (busy || !isConnected) return;+ if (busy || !isConnected || awaitingReconnectRef.current) return;if (operation === 'delete' && !window.confirm(t('a2aIngress.outbound.deleteConfirm'))) return;setBusy(`${operation}:${agent.agent_id}`);setError(null);setNotice(null);generationRef.current.next();+ const generation = userScopeRef.current.next();try {let payload: unknown;if (operation === 'toggle') {@@ -219,6 +242,7 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainerelse if (operation === 'confirm' || operation === 'reject')payload = await request('a2a.outbound.confirm_revision', { agent_id: agent.agent_id, accept: operation === 'confirm' });else payload = await request('a2a.outbound.delete', { agent_id: agent.agent_id });+ if (!userScopeRef.current.accepts(generation)) return;if (operation === 'delete') setAgents(current => current.filter(item => item.agent_id !== agent.agent_id));else {const updated = normalizeA2AOutboundAgent(payload);@@ -226,10 +250,11 @@ export function A2AOutboundPanel({ isConnected, request, headerActionsContainersetAgents(current => current.map(item => (item.agent_id === updated.agent_id ? updated : item)));}} catch (nextError) {+ if (!userScopeRef.current.accepts(generation)) return;setError(errorMessage(nextError));void refresh();} finally {- setBusy(null);+ if (userScopeRef.current.accepts(generation)) setBusy(null);}};diff --git a/jiuwenswarm/gateway/a2a_manager/manager.py b/jiuwenswarm/gateway/a2a_manager/manager.pyindex 4165f98c1f..b62c87662f 100644--- a/jiuwenswarm/gateway/a2a_manager/manager.py+++ b/jiuwenswarm/gateway/a2a_manager/manager.py@@ -164,10 +164,11 @@ class A2AManager:return await self._require_outbound().register(params)async def outbound_list(- self, *, source_resource_id: str | None = None+ self, *, 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)outbound = self._require_outbound()- result = await outbound.list_agents()+ result = await outbound.list_agents(source_user_id=source_user_id)allowed = await self._resolve_authorized_a2a_agent_ids(source_resource_id)if allowed is None:return result@@ -187,11 +188,15 @@ class A2AManager:*,enabled: bool,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)allowed = await self._resolve_authorized_a2a_agent_ids(source_resource_id)if allowed is not None and str(agent_id or "").strip() not in allowed:raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)- return await self._require_outbound().set_user_enabled(agent_id, enabled)+ return await self._require_outbound().set_user_enabled(+ agent_id, enabled, source_user_id=source_user_id+ )async def outbound_edit(self, agent_id: str) -> dict[str, Any]:return await self._require_outbound().edit_agent(agent_id)@@ -259,8 +264,10 @@ class A2AManager:required_skills: list[str] | None = None,limit: int = 5,source_resource_id: str | None = None,+ source_user_id: str | None = None,) -> dict[str, Any]:- allowed = await self._resolve_effective_a2a_agent_ids(source_resource_id)+ source_user_id = self._history_user_id(source_user_id)+ allowed = await self._resolve_effective_a2a_agent_ids(source_resource_id, source_user_id)return await self._require_outbound_dispatcher().find_agents(query=query,required_skills=required_skills,@@ -280,7 +287,7 @@ class A2AManager: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)+ await self._require_a2a_agent_authorized(source_resource_id, agent_id, source_user_id)return await self._require_outbound_dispatcher().dispatch(agent_id=agent_id,task=task,@@ -310,13 +317,13 @@ class A2AManager:)async def _resolve_effective_a2a_agent_ids(- self, resource_id: str | None+ self, resource_id: str | None, source_user_id: str | None = None) -> frozenset[str] | None:outbound = self._outboundif outbound is None:return Nonereturn await outbound.resolve_effective_a2a_agent_ids(- str(resource_id or "").strip()+ str(resource_id or "").strip(), source_user_id=source_user_id)async def _resolve_authorized_a2a_agent_ids(@@ -331,16 +338,18 @@ class A2AManager:return await resolver(str(resource_id or "").strip())async def _require_a2a_agent_authorized(- self, resource_id: str | None, agent_id: str+ self, resource_id: str | None, agent_id: str, source_user_id: str | None = None) -> None:- allowed = await self._resolve_effective_a2a_agent_ids(resource_id)+ allowed = await self._resolve_effective_a2a_agent_ids(resource_id, source_user_id)normalized_agent_id = str(agent_id or "").strip()if allowed is None or normalized_agent_id in allowed:returnauthorized = await self._resolve_authorized_a2a_agent_ids(resource_id)if authorized is not None and normalized_agent_id not in authorized:raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_AUTHORIZED)- projected = await self._require_outbound().get_agent(normalized_agent_id)+ projected = await self._require_outbound().get_agent(+ normalized_agent_id, source_user_id=source_user_id+ )if projected.get("manager_enabled") is False:raise A2AOutboundError(A2AOutboundErrorCode.AGENT_MANAGER_DISABLED)if projected.get("user_enabled") is False:diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.pyindex 5bf8f36cc0..8623c84329 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py@@ -293,7 +293,7 @@ class A2AOutboundDispatcher:session_id = str(source_session_id or "").strip()if not session_id:raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_REJECTED)- agent = await self._require_callable_agent(agent_id)+ agent = await self._require_callable_agent(agent_id, source_user_id=source_user_id)self._schedule_cleanup_dispatches()dispatch_id = f"disp_{uuid.uuid4().hex}"@@ -823,8 +823,16 @@ class A2AOutboundDispatcher:return headers, params, cookiesraise A2AOutboundError(A2AOutboundErrorCode.AUTH_REQUIRED)- async def _require_callable_agent(self, agent_id: str) -> A2AOutboundAgent:- agent = await self._repository.get_agent(str(agent_id or "").strip())+ async def _require_callable_agent(+ self, agent_id: str, *, source_user_id: str | None = None+ ) -> A2AOutboundAgent:+ normalized = str(agent_id or "").strip()+ get_projected = getattr(self._repository, "get_projected_agent", None)+ if callable(get_projected):+ projected = await get_projected(normalized, source_user_id=source_user_id)+ agent = projected.agent if projected is not None else None+ else:+ agent = await self._repository.get_agent(normalized)if agent is None:raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)if not agent.enabled:diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py b/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.pyindex aed1237fc0..9da7b63443 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/enterprise.py@@ -120,10 +120,10 @@ class EnterpriseA2AProjection(A2AOutboundRepository):self._instance_resources = instance_resourcesasync def resolve_effective_a2a_agent_ids(- self, resource_id: str+ self, resource_id: str, *, source_user_id: str | None = None) -> frozenset[str]:"""Resolve the current policy/manager/user intersection for one resource."""- allowed, projected = await self._resolve_policy_scope(resource_id)+ allowed, projected = await self._resolve_policy_scope(resource_id, source_user_id=source_user_id)effective_ids = []for item in projected:if item.agent.agent_id not in allowed:@@ -143,7 +143,7 @@ class EnterpriseA2AProjection(A2AOutboundRepository):return allowedasync def _resolve_policy_scope(- self, resource_id: str+ self, resource_id: str, *, source_user_id: str | None = None) -> tuple[frozenset[str], list[EnterpriseA2AAgentView]]:if not all((self._policies, self._agent_templates, self._instance_resources)):return frozenset(), []@@ -180,7 +180,7 @@ class EnterpriseA2AProjection(A2AOutboundRepository):for item in (policy.get("member_template_ids") or [])if str(item).strip()}- projected = await self.list_projected_agents()+ projected = await self.list_projected_agents(source_user_id=source_user_id)mode = str(policy.get("mode") or "").strip().lower()if mode == "allowlist":policy_allowed = members@@ -259,25 +259,29 @@ class EnterpriseA2AProjection(A2AOutboundRepository):)async def get_projected_agent(- self, template_id: str+ self, template_id: str, *, source_user_id: str | None = None) -> EnterpriseA2AAgentView | None:normalized = str(template_id or "").strip()template = await self._templates.get(template_id=normalized)if template is None:return None- user_state, runtime_state = await asyncio.gather(- self._user_states.get(template_id=normalized),- self._runtime_states.get(template_id=normalized),+ # System catalog reads do not inherit the old, unowned shared switch.+ user_state = (+ await self._user_states.get(template_id=normalized, user_id=source_user_id)+ if source_user_id else None)+ runtime_state = await self._runtime_states.get(template_id=normalized)return self._project(template, user_state, runtime_state)- async def list_projected_agents(self) -> list[EnterpriseA2AAgentView]:+ async def list_projected_agents(+ self, *, source_user_id: str | None = None+ ) -> list[EnterpriseA2AAgentView]:templates, user_rows, runtime_rows = await asyncio.gather(self._templates.list(order_by="updated_at DESC"),- self._user_states.list(),+ self._user_states.list(filters={"user_id": source_user_id}),self._runtime_states.list(),)- user_states = {row["template_id"]: row for row in user_rows}+ user_states = {row["template_id"]: row for row in user_rows} if source_user_id else {}runtime_states = {row["template_id"]: row for row in runtime_rows}return [self._project(@@ -296,8 +300,11 @@ class EnterpriseA2AProjection(A2AOutboundRepository):return [item.agent for item in await self.list_projected_agents()]async def set_user_enabled(- self, template_id: str, user_enabled: bool+ self, template_id: str, user_enabled: bool, *, source_user_id: str | None = None) -> EnterpriseA2AAgentView:+ source_user_id = str(source_user_id or "").strip()+ if not source_user_id:+ raise A2AOutboundError(A2AOutboundErrorCode.USER_IDENTITY_REQUIRED)if not isinstance(user_enabled, bool):raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)normalized = str(template_id or "").strip()@@ -306,11 +313,12 @@ class EnterpriseA2AProjection(A2AOutboundRepository):await self._user_states.upsert({"template_id": normalized,+ "user_id": source_user_id,"user_enabled": user_enabled,"updated_at": _utc_now(),})- projected = await self.get_projected_agent(normalized)+ projected = await self.get_projected_agent(normalized, source_user_id=source_user_id)if projected is None:raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)return projected@@ -350,10 +358,9 @@ class EnterpriseA2AProjection(A2AOutboundRepository):async def clear_agent_state(self, template_id: str) -> None:key = {"template_id": str(template_id or "").strip()}- await asyncio.gather(- self._user_states.delete(key),- self._runtime_states.delete(key),- )+ for row in await self._user_states.list(filters=key):+ await self._user_states.delete(**key, user_id=row.get("user_id"))+ await self._runtime_states.delete(key)async def create_agent(self, agent: A2AOutboundAgent) -> A2AOutboundAgent:del agentdiff --git a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py b/jiuwenswarm/gateway/a2a_manager/outbound/registry.pyindex cdba5baf2f..36ce3be60a 100644--- a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py+++ b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py@@ -204,40 +204,40 @@ class A2AOutboundRegistry:)return created.public_dict()- async def list_agents(self) -> dict[str, Any]:+ async def list_agents(self, *, source_user_id: str | None = None) -> dict[str, Any]:list_projected = getattr(self._repository, "list_projected_agents", None)if callable(list_projected):- projected = await list_projected()+ projected = await list_projected(source_user_id=source_user_id)items = [item.public_dict() for item in projected]return {"items": items, "total": len(items)}items = [item.public_dict() for item in await self._repository.list_agents()]return {"items": items, "total": len(items)}- async def get_agent(self, agent_id: str) -> dict[str, Any]:+ async def get_agent(self, agent_id: str, *, source_user_id: str | None = None) -> dict[str, Any]:get_projected = getattr(self._repository, "get_projected_agent", None)if callable(get_projected):- projected = await get_projected(agent_id)+ projected = await get_projected(agent_id, source_user_id=source_user_id)if projected is None:raise A2AOutboundError(A2AOutboundErrorCode.AGENT_NOT_REGISTERED)return projected.public_dict()return (await self._require_agent(agent_id)).public_dict()async def set_user_enabled(- self, agent_id: str, user_enabled: bool+ self, agent_id: str, user_enabled: bool, *, source_user_id: str | None = None) -> dict[str, Any]:setter = getattr(self._repository, "set_user_enabled", None)if not callable(setter):raise A2AOutboundError(A2AOutboundErrorCode.STORE_INVALID)- projected = await setter(agent_id, user_enabled)+ projected = await setter(agent_id, user_enabled, source_user_id=source_user_id)return projected.public_dict()async def resolve_effective_a2a_agent_ids(- self, resource_id: str+ self, resource_id: str, *, source_user_id: str | None = None) -> frozenset[str] | None:resolver = getattr(self._repository, "resolve_effective_a2a_agent_ids", None)if not callable(resolver):return None- return await resolver(resource_id)+ return await resolver(resource_id, source_user_id=source_user_id)async def resolve_authorized_a2a_agent_ids(self, resource_id: strdiff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex e975d3e51c..c6e0fd6a08 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1985,11 +1985,12 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:ws, req_id, lambda: a2a_manager.outbound_register(dict(params)))- async def _a2a_outbound_list(ws, req_id, params, session_id):+ async def _a2a_outbound_list(ws, req_id, params, session_id, user_id=None):await _send_a2a_outbound(ws,req_id,lambda: a2a_manager.outbound_list(+ source_user_id=user_id,source_resource_id=(str(params.get("bot_id") or "") if is_enterprise() else None)@@ -2013,7 +2014,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:ws, req_id, lambda: a2a_manager.outbound_update(agent_id, payload))- async def _a2a_outbound_enabled_update(ws, req_id, params, session_id):+ async def _a2a_outbound_enabled_update(ws, req_id, params, session_id, user_id=None):user_enabled = params.get("user_enabled")if not isinstance(user_enabled, bool):await channel.send_response(@@ -2030,6 +2031,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:lambda: a2a_manager.outbound_set_user_enabled(str(params.get("agent_id") or ""),enabled=user_enabled,+ source_user_id=user_id,source_resource_id=(str(params.get("bot_id") or "") if is_enterprise() else None),diff --git a/jiuwenswarm/gateway/config/enterprise/catalog.py b/jiuwenswarm/gateway/config/enterprise/catalog.pyindex a71776b7fa..972e2c9e77 100644--- a/jiuwenswarm/gateway/config/enterprise/catalog.py+++ b/jiuwenswarm/gateway/config/enterprise/catalog.py@@ -34,7 +34,7 @@ ENTERPRISE_RECORD_SPECS: dict[str, EnterpriseRecordSpec] = {"agent_template": EnterpriseRecordSpec(key_fields=("template_id",)),"a2a_outbound_template": EnterpriseRecordSpec(key_fields=("template_id",)),"a2a_access_policy_template": EnterpriseRecordSpec(key_fields=("policy_id",)),- "a2a_outbound_user_state": EnterpriseRecordSpec(key_fields=("template_id",)),+ "a2a_outbound_user_state": EnterpriseRecordSpec(key_fields=("template_id", "user_id")),"a2a_outbound_runtime_state": EnterpriseRecordSpec(key_fields=("template_id",)),"a2a_outbound_dispatch": EnterpriseRecordSpec(key_fields=("dispatch_id",)),"instance_agent_resource": EnterpriseRecordSpec(key_fields=("resource_id",)),diff --git a/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py b/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.pyindex 3b37a0a313..158759d181 100644--- a/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py+++ b/jiuwenswarm/gateway/config/enterprise/tables/a2a_migration.py@@ -1,10 +1,56 @@-"""Upgrade only A2A history ownership; legacy rows remain unowned."""+"""Upgrade A2A user ownership; legacy rows remain unowned."""from sqlalchemy import inspect, textfrom sqlalchemy.exc import DBAPIErrorfrom sqlalchemy.ext.asyncio import AsyncEngine-from .a2a_models import A2A_OUTBOUND_DISPATCH_TABLE_DEF+from .a2a_models import A2A_OUTBOUND_DISPATCH_TABLE_DEF, A2A_OUTBOUND_USER_STATE_TABLE_DEF+++async def ensure_user_state_identity(engine: AsyncEngine) -> None:+ """Replace the template-only unique index with a per-user identity."""+ table_name = A2A_OUTBOUND_USER_STATE_TABLE_DEF.table_name+ index_name = f"ix_{table_name}_template_id_user_id"++ def upgrade(connection):+ inspector = inspect(connection)+ if not inspector.has_table(table_name):+ return+ quote = connection.dialect.identifier_preparer.quote+ table = quote(table_name)+ if not any(col["name"] == "user_id" for col in inspector.get_columns(table_name)):+ connection.execute(text(f"ALTER TABLE {table} ADD COLUMN user_id VARCHAR(256) NULL"))+ indexes = inspector.get_indexes(table_name)+ # Create the replacement before removing the old uniqueness constraint.+ if not any(+ idx["unique"] and idx["column_names"] == ["template_id", "user_id"]+ for idx in indexes+ ):+ connection.execute(text(+ f"CREATE UNIQUE INDEX {quote(index_name)} ON {table} (template_id, user_id)"+ ))+ for idx in indexes:+ if idx["unique"] and idx["column_names"] == ["template_id"]:+ suffix = f" ON {table}" if connection.dialect.name == "mysql" else ""+ connection.execute(text(f"DROP INDEX {quote(idx['name'])}{suffix}"))++ def ready(connection):+ inspector = inspect(connection)+ indexes = inspector.get_indexes(table_name)+ return (+ any(col["name"] == "user_id" for col in inspector.get_columns(table_name))+ and any(idx["unique"] and idx["column_names"] == ["template_id", "user_id"] for idx in indexes)+ and not any(idx["unique"] and idx["column_names"] == ["template_id"] for idx in indexes)+ )++ try:+ async with engine.begin() as connection:+ await connection.run_sync(upgrade)+ except DBAPIError:+ # Only tolerate concurrent upgrades after verifying the complete schema.+ async with engine.connect() as connection:+ if not await connection.run_sync(ready):+ raiseasync def ensure_dispatch_user_column(engine: AsyncEngine) -> None:diff --git a/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py b/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.pyindex 34c2f1f278..171fe51015 100644--- a/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py+++ b/jiuwenswarm/gateway/config/enterprise/tables/a2a_models.py@@ -18,10 +18,11 @@ A2A_OUTBOUND_USER_STATE_TABLE_DEF = TableDefinition("id", "integer", primary_key=True, autoincrement=True, nullable=False),ColumnDefinition("template_id", "string", length=100, nullable=False),+ ColumnDefinition("user_id", "string", length=256, nullable=True),ColumnDefinition("user_enabled", "boolean", nullable=False, default=True),ColumnDefinition("updated_at", "datetime", nullable=False),],- indexes=[IndexDefinition(["template_id"], unique=True)],+ indexes=[IndexDefinition(["template_id", "user_id"], unique=True)],)A2A_OUTBOUND_RUNTIME_STATE_TABLE_DEF = TableDefinition(diff --git a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py b/jiuwenswarm/gateway/config/enterprise/tables/table_init.pyindex 5136c26a04..76fd0e81a9 100644--- a/jiuwenswarm/gateway/config/enterprise/tables/table_init.py+++ b/jiuwenswarm/gateway/config/enterprise/tables/table_init.py@@ -8,7 +8,7 @@ from __future__ import annotationsfrom openjiuwen_runtime.foundation.db.handler import DBHandlerfrom openjiuwen_runtime.foundation.db.table_def import TableDefinition-from .a2a_migration import ensure_dispatch_user_column+from .a2a_migration import ensure_dispatch_user_column, ensure_user_state_identityfrom .a2a_models import (A2A_OUTBOUND_DISPATCH_TABLE_DEF,A2A_OUTBOUND_RUNTIME_STATE_TABLE_DEF,@@ -71,6 +71,8 @@ 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_USER_STATE_TABLE_DEF:+ await ensure_user_state_identity(handler.get_engine())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 15f372a978..fd02a9e51c 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -3164,7 +3164,7 @@ class MessageHandler(FileTransferMixin, ABC):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:+ if is_enterprise() and not source_user_id:raise A2AOutboundError(A2AOutboundErrorCode.USER_IDENTITY_REQUIRED)if manager is None:raise A2AOutboundError(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)@@ -3182,6 +3182,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_find_agents(**call_params)elif method == A2A_TOOL_DISPATCH_TASK:call_params = {diff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.pyindex 86656986b6..f1caa81ea2 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/core/template/a2a_outbound_template.py@@ -150,7 +150,7 @@ class A2AOutboundTemplateService:user_states = require_enterprise_repository(_USER_STATE_TABLE)runtime_states = require_enterprise_repository(_RUNTIME_STATE_TABLE)existing = await repo.get(template_id=tid)- old_user_state = await user_states.get(template_id=tid)+ old_user_states = await user_states.list(filters={"template_id": tid})old_runtime_state = await runtime_states.get(template_id=tid)credential_ref = (str(existing.get("credential_ref") or "")@@ -162,15 +162,17 @@ class A2AOutboundTemplateService:self._credentials.delete(credential_ref)if existing is not None:await repo.delete(template_id=tid)- await user_states.delete(template_id=tid)+ for row in old_user_states:+ await user_states.delete(template_id=tid, user_id=row.get("user_id"))await runtime_states.delete(template_id=tid)except Exception:try:projection = _row_for_restore(existing, "created_at", "updated_at")if projection is not None:await repo.upsert(projection)- user_state = _row_for_restore(old_user_state, "updated_at")- if user_state is not None:+ for row in old_user_states:+ user_state = _row_for_restore(row, "updated_at")+ user_state.setdefault("user_id", None)await user_states.upsert(user_state)runtime_state = _row_for_restore(old_runtime_state,diff --git a/tests/unit_tests/gateway/test_a2a_history_migration.py b/tests/unit_tests/gateway/test_a2a_history_migration.pyindex 016afb1d15..60778f54f8 100644--- a/tests/unit_tests/gateway/test_a2a_history_migration.py+++ b/tests/unit_tests/gateway/test_a2a_history_migration.py@@ -84,6 +84,14 @@ class _SQLiteConnection:def execute(self, statement):return self.db.execute(statement)+ def get_indexes(self, name):+ return [+ {"name": row[1], "unique": bool(row[2]), "column_names": [+ col[2] for col in self.db.execute(f"PRAGMA index_info({row[1]})")+ ]}+ for row in self.db.execute(f"PRAGMA index_list({name})")+ ]+@pytest.mark.asyncio@pytest.mark.parametrize("owner_length", [None, 64, 256])@@ -196,3 +204,71 @@ async def test_failed_widening_requires_verified_final_length(monkeypatch, migraawait a2a_migration.ensure_dispatch_user_column(engine)assert caught.value is failureassert events == ["rollback", "verify"]+++async def test_user_state_migration_preserves_unowned_rows_and_is_idempotent(migration):+ with closing(sqlite3.connect(":memory:")) as db:+ db.execute("CREATE TABLE a2a_outbound_user_state (id INTEGER PRIMARY KEY, "+ "template_id VARCHAR(100), user_enabled BOOLEAN, updated_at DATETIME)")+ db.execute("CREATE UNIQUE INDEX ix_a2a_outbound_user_state_template_id "+ "ON a2a_outbound_user_state(template_id)")+ db.execute("INSERT INTO a2a_outbound_user_state VALUES (1, 'agent', 0, 'old')")+ connection = _SQLiteConnection(db)++ @asynccontextmanager+ async def begin():+ with db:+ yield connection++ engine = SimpleNamespace(begin=begin, connect=begin)+ await migration.ensure_user_state_identity(engine)+ await migration.ensure_user_state_identity(engine)+ assert db.execute("SELECT user_id, user_enabled FROM a2a_outbound_user_state").fetchall() == [(None, 0)]+ for owner, enabled in [("user-a", 0), ("u" * 256, 1)]:+ db.execute("INSERT INTO a2a_outbound_user_state(template_id, user_id, user_enabled) "+ "VALUES ('agent', ?, ?)", (owner, enabled))+ with pytest.raises(sqlite3.IntegrityError):+ db.execute("INSERT INTO a2a_outbound_user_state(template_id, user_id) VALUES ('agent', 'user-a')")+ await migration.ensure_user_state_identity(engine)+ assert db.execute("SELECT COUNT(*) FROM a2a_outbound_user_state").fetchone()[0] == 3++[email protected]("dialect_name", ["mysql", "postgresql"])+async def test_user_state_migration_replaces_template_index(monkeypatch, migration, dialect_name):+ columns = [{"name": "template_id"}]+ indexes = [{"name": "old_unique", "unique": True, "column_names": ["template_id"]}]+ statements = []+ inspector = SimpleNamespace(+ has_table=lambda name: True, get_columns=lambda name: columns,+ get_indexes=lambda name: list(indexes),+ )+ monkeypatch.setattr(migration, "inspect", lambda connection: inspector)++ class Connection:+ dialect = _dialect(dialect_name)++ async def run_sync(self, callback):+ return callback(self)++ def execute(self, statement):+ statements.append(statement)+ if "ADD COLUMN" in statement:+ columns.append({"name": "user_id"})+ elif "CREATE UNIQUE INDEX" in statement:+ indexes.append({"name": "new_unique", "unique": True,+ "column_names": ["template_id", "user_id"]})+ elif "DROP INDEX" in statement:+ indexes[:] = [index for index in indexes if index["name"] != "old_unique"]++ @asynccontextmanager+ async def begin():+ yield Connection()++ engine = SimpleNamespace(begin=begin, connect=begin)+ await migration.ensure_user_state_identity(engine)+ await migration.ensure_user_state_identity(engine)+ assert len(statements) == 3+ suffix = " ON a2a_outbound_user_state" if dialect_name == "mysql" else ""+ assert statements[-1] == f"DROP INDEX old_unique{suffix}"diff --git a/tests/unit_tests/gateway/test_a2a_manager.py b/tests/unit_tests/gateway/test_a2a_manager.pyindex c08f4a4d08..0f967d6081 100644--- a/tests/unit_tests/gateway/test_a2a_manager.py+++ b/tests/unit_tests/gateway/test_a2a_manager.py@@ -929,7 +929,7 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")class _Registry:- async def resolve_effective_a2a_agent_ids(self, resource_id):+ async def resolve_effective_a2a_agent_ids(self, resource_id, *, source_user_id=None):assert resource_id == "resource-1"return frozenset({"agent-1"})@@ -937,20 +937,20 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(assert resource_id == "resource-1"return frozenset({"agent-1", "agent-manager", "agent-user"})- async def list_agents(self):+ async def list_agents(self, *, source_user_id=None):return {"items": [{"agent_id": "agent-1"}, {"agent_id": "agent-2"}],"total": 2,}- async def get_agent(self, agent_id):+ async def get_agent(self, agent_id, *, source_user_id=None):return {"agent_id": agent_id,"manager_enabled": agent_id != "agent-manager","user_enabled": agent_id != "agent-user",}- async def set_user_enabled(self, agent_id, enabled):+ async def set_user_enabled(self, agent_id, enabled, *, source_user_id=None):return {"agent_id": agent_id, "user_enabled": enabled}class _Dispatcher:@@ -967,9 +967,9 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(manager._outbound = _Registry()manager._outbound_dispatcher = _Dispatcher()- found = await manager.outbound_find_agents(source_resource_id="resource-1")+ found = await manager.outbound_find_agents(source_resource_id="resource-1", source_user_id="user-1")assert found["allowed_agent_ids"] == frozenset({"agent-1"})- listed = await manager.outbound_list(source_resource_id="resource-1")+ listed = await manager.outbound_list(source_resource_id="resource-1", source_user_id="user-1")assert listed == {"items": [{"agent_id": "agent-1"}], "total": 1}dispatched = await manager.outbound_dispatch_task(agent_id="agent-1",@@ -1034,6 +1034,6 @@ async def test_enterprise_outbound_tools_enforce_resource_policy(with pytest.raises(A2AOutboundError) as exc_info:await manager.outbound_set_user_enabled(- "agent-2", enabled=True, source_resource_id="resource-1"+ "agent-2", enabled=True, source_resource_id="resource-1", source_user_id="user-1")assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_AUTHORIZEDdiff --git a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.pyindex a7adabd3f3..7ecae4c9ce 100644--- a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py+++ b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py@@ -151,7 +151,7 @@ class _OutboundRegistryProbe:async def register(self, params):return {"agent_id": "agent-1", "display_name": params.get("display_name")}- async def list_agents(self):+ async def list_agents(self, *, source_user_id=None):return {"items": [], "total": 0}async def get_agent(self, agent_id):@@ -160,7 +160,7 @@ class _OutboundRegistryProbe:async def update_agent(self, agent_id, params):return {"agent_id": agent_id, **params}- async def set_user_enabled(self, agent_id, user_enabled):+ async def set_user_enabled(self, agent_id, user_enabled, *, source_user_id=None):return {"agent_id": agent_id,"user_enabled": user_enabled,diff --git a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.pyindex e90a7082fa..b12b0d4f32 100644--- a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py+++ b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py@@ -976,7 +976,7 @@ async def test_enterprise_dispatch_requires_user_and_hides_other_and_legacy_reco@pytest.mark.asyncio[email protected]("method", [A2A_TOOL_DISPATCH_TASK, A2A_TOOL_GET_DISPATCH])[email protected]("method", [A2A_TOOL_FIND_AGENTS, A2A_TOOL_DISPATCH_TASK, A2A_TOOL_GET_DISPATCH])@pytest.mark.parametrize("fallback", [False, True])async def test_enterprise_reverse_rpc_uses_context_user_not_tool_params(monkeypatch, method, fallback@@ -990,6 +990,7 @@ async def test_enterprise_reverse_rpc_uses_context_user_not_tool_params(return {}outbound_get_dispatch = outbound_dispatch_task+ outbound_find_agents = outbound_dispatch_taskhandler = object.__new__(MessageHandler)handler._a2a_outbound_tool_manager = Manager()@@ -1232,7 +1233,7 @@ async def test_toolkit_missing_route_is_not_reported_as_remote_rejection() -> No@pytest.mark.asyncio[email protected]("method", [A2A_TOOL_DISPATCH_TASK, A2A_TOOL_GET_DISPATCH])[email protected]("method", [A2A_TOOL_FIND_AGENTS, A2A_TOOL_DISPATCH_TASK, A2A_TOOL_GET_DISPATCH])async def test_gateway_backend_leaves_operation_timeout_to_manager(monkeypatch, method) -> None:@@ -1437,10 +1438,11 @@ async def test_enterprise_gateway_bridge_binds_trusted_resource_id(monkeypatch)await handler._handle_a2a_outbound_tool_push(chunk=chunk,session_id="session-1",- request_metadata={"routing": {"bot_id": "resource-1"}},+ request_metadata={"user_id": "user-1", "routing": {"bot_id": "resource-1"}},)assert calls[0]["source_resource_id"] == "resource-1"+ assert calls[0]["source_user_id"] == "user-1"assert replies[0].params["response"]["result"]["total"] == 0diff --git a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.pyindex b2c8e28872..b09b2571ca 100644--- a/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py+++ b/tests/unit_tests/gateway/test_manager_config_receiver_a2a.py@@ -239,7 +239,7 @@ async def test_invalid_network_policy_does_not_break_enterprise_directory(assert set(agents) == {"a2a-weather", "invalid-policy-agent"}assert agents["invalid-policy-agent"].network_policy == {}assert "Invalid A2A network_policy template_id=invalid-policy-agent" in caplog.text- direct = await projection.get_projected_agent("invalid-policy-agent")+ direct = await projection.get_projected_agent("invalid-policy-agent", source_user_id="user-1")assert direct.agent.network_policy == {}@@ -304,6 +304,7 @@ def test_a2a_outbound_receiver_crud_and_secret_store(lambda: user_states.create({"template_id": "a2a-weather",+ "user_id": "user-1","user_enabled": False,"updated_at": "2026-09-05T00:00:00Z",}@@ -326,7 +327,7 @@ def test_a2a_outbound_receiver_crud_and_secret_store(assert client.request("DELETE", f"{path}/a2a-weather", json={}).status_code == 200assert client.portal.call(- lambda: user_states.get(template_id="a2a-weather")+ lambda: user_states.get(template_id="a2a-weather", user_id="user-1")) is Noneassert client.portal.call(lambda: runtime_states.get(template_id="a2a-weather")@@ -589,7 +590,7 @@ async def test_enterprise_projection_merges_manager_user_and_runtime_state() ->)registry = A2AOutboundRegistry(projection)- initial = await projection.get_projected_agent("a2a-weather")+ initial = await projection.get_projected_agent("a2a-weather", source_user_id="user-1")assert initial is not Noneassert initial.manager_enabled is Trueassert initial.user_enabled is True@@ -600,15 +601,15 @@ async def test_enterprise_projection_merges_manager_user_and_runtime_state() ->await repos["a2a_outbound_template"].update({"template_id": "a2a-weather"}, {"data": {"network_policy": network_policy}})- updated_policy = await projection.get_projected_agent("a2a-weather")+ updated_policy = await projection.get_projected_agent("a2a-weather", source_user_id="user-1")assert updated_policy.agent.network_policy == network_policyawait repos["a2a_outbound_template"].update({"template_id": "a2a-weather"}, {"data": {"network_policy": {}}})- revoked_policy = await projection.get_projected_agent("a2a-weather")+ revoked_policy = await projection.get_projected_agent("a2a-weather", source_user_id="user-1")assert revoked_policy.agent.network_policy == {}- disabled = await projection.set_user_enabled("a2a-weather", False)+ disabled = await projection.set_user_enabled("a2a-weather", False, source_user_id="user-1")assert disabled.manager_enabled is Trueassert disabled.user_enabled is Falseassert disabled.effective_enabled is False@@ -617,20 +618,20 @@ async def test_enterprise_projection_merges_manager_user_and_runtime_state() ->)assert isinstance(user_row["updated_at"], datetime)with pytest.raises(A2AOutboundError) as exc_info:- await projection.set_user_enabled("missing-agent", True)+ await projection.set_user_enabled("missing-agent", True, source_user_id="user-1")assert exc_info.value.code is A2AOutboundErrorCode.AGENT_NOT_REGISTEREDawait repos["a2a_outbound_template"].update({"template_id": "a2a-weather"},{"template_name": "Weather Agent v2", "card_revision": 2},)- persisted = await projection.get_projected_agent("a2a-weather")+ persisted = await projection.get_projected_agent("a2a-weather", source_user_id="user-1")assert persisted is not None and persisted.user_enabled is False- await projection.set_user_enabled("a2a-weather", True)+ await projection.set_user_enabled("a2a-weather", True, source_user_id="user-1")await repos["a2a_outbound_template"].update({"template_id": "a2a-weather"}, {"enabled": False})- manager_disabled = await projection.get_projected_agent("a2a-weather")+ manager_disabled = await projection.get_projected_agent("a2a-weather", source_user_id="user-1")assert manager_disabled is not Noneassert manager_disabled.manager_enabled is Falseassert manager_disabled.user_enabled is True@@ -642,7 +643,7 @@ async def test_enterprise_projection_merges_manager_user_and_runtime_state() ->A2AOutboundAvailability.UNREACHABLE,error_code=A2AOutboundErrorCode.CARD_FETCH_FAILED.value,)- runtime_failed = await projection.get_projected_agent("a2a-weather")+ runtime_failed = await projection.get_projected_agent("a2a-weather", source_user_id="user-1")assert runtime_failed is not Noneassert runtime_failed.agent.availability is A2AOutboundAvailability.UNREACHABLEassert runtime_failed.agent.last_error_summary == "无法获取第三方 Agent Card。"@@ -705,14 +706,14 @@ async def test_enterprise_projection_reuses_dispatch_repository() -> None:assert isinstance(dispatch_row["accepted_at"], datetime)assert isinstance(dispatch_row["finished_at"], datetime)- await projection.set_user_enabled("a2a-weather", False)+ await projection.set_user_enabled("a2a-weather", False, source_user_id="user-1")restarted = EnterpriseA2AProjection(store,templates=repos["a2a_outbound_template"],user_states=repos["a2a_outbound_user_state"],runtime_states=repos["a2a_outbound_runtime_state"],)- restored_after_restart = await restarted.get_projected_agent("a2a-weather")+ restored_after_restart = await restarted.get_projected_agent("a2a-weather", source_user_id="user-1")assert restored_after_restart is not Noneassert restored_after_restart.user_enabled is Falseassert (await restarted.get_dispatch("dispatch-1")) is not None@@ -800,6 +801,7 @@ def test_a2a_delete_restores_projection_and_local_state_on_cleanup_failure(lambda: user_states.create({"template_id": "a2a-weather",+ "user_id": "user-1","user_enabled": False,"updated_at": datetime.now(timezone.utc),}@@ -835,7 +837,7 @@ def test_a2a_delete_restores_projection_and_local_state_on_cleanup_failure(is not None)assert (- client.portal.call(lambda: user_states.get(template_id="a2a-weather"))[+ client.portal.call(lambda: user_states.get(template_id="a2a-weather", user_id="user-1"))["user_enabled"]is False@@ -848,7 +850,7 @@ def test_a2a_delete_restores_projection_and_local_state_on_cleanup_failure(monkeypatch.setattr(runtime_states, "delete", original_delete)client.portal.call(lambda: service.delete("a2a-weather"))assert (- client.portal.call(lambda: user_states.get(template_id="a2a-weather")) is None+ client.portal.call(lambda: user_states.get(template_id="a2a-weather", user_id="user-1")) is None)@@ -916,18 +918,18 @@ async def test_enterprise_projection_resolves_policy_manager_and_user_intersectiinstance_resources=repos["instance_agent_resource"],)- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == {+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == {"a2a-weather","a2a-calendar",}await repos["a2a_access_policy_template"].update({"policy_id": "policy-1"}, {"member_template_ids": []})- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == frozenset()await repos["a2a_access_policy_template"].update({"policy_id": "policy-1"}, {"mode": "denylist"})- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == {+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == {"a2a-weather","a2a-calendar",}@@ -941,19 +943,19 @@ async def test_enterprise_projection_resolves_policy_manager_and_user_intersectiawait repos["instance_agent_resource"].update({"resource_id": "resource-1"}, {"enabled": False})- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == frozenset()await repos["instance_agent_resource"].update({"resource_id": "resource-1"},{"enabled": True, "expires_at": datetime(2020, 1, 1, tzinfo=timezone.utc)},)- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == frozenset()await repos["instance_agent_resource"].update({"resource_id": "resource-1"}, {"expires_at": None})await repos["a2a_access_policy_template"].update({"policy_id": "policy-1"}, {"enabled": False})- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == frozenset()await repos["a2a_access_policy_template"].update({"policy_id": "policy-1"}, {"enabled": True})@@ -961,7 +963,7 @@ async def test_enterprise_projection_resolves_policy_manager_and_user_intersecti{"policy_id": "policy-1"},{"mode": "denylist", "member_template_ids": ["a2a-weather"]},)- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == {+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == {"a2a-calendar"}await repos["a2a_access_policy_template"].update(@@ -971,14 +973,14 @@ async def test_enterprise_projection_resolves_policy_manager_and_user_intersecti"member_template_ids": ["a2a-weather", "a2a-calendar"],},)- await projection.set_user_enabled("a2a-calendar", False)- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == {+ await projection.set_user_enabled("a2a-calendar", False, source_user_id="user-1")+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == {"a2a-weather"}await repos["a2a_outbound_template"].update({"template_id": "a2a-weather"}, {"enabled": False})- assert await projection.resolve_effective_a2a_agent_ids("resource-1") == frozenset()+ assert await projection.resolve_effective_a2a_agent_ids("resource-1", source_user_id="user-1") == frozenset()assert await projection.resolve_authorized_a2a_agent_ids("resource-1") == {"a2a-weather","a2a-calendar",@@ -999,7 +1001,7 @@ async def test_enterprise_projection_fails_closed_for_invalid_resource_or_policyinstance_resources=repos["instance_agent_resource"],)- assert await projection.resolve_effective_a2a_agent_ids("missing") == frozenset()+ assert await projection.resolve_effective_a2a_agent_ids("missing", source_user_id="user-1") == frozenset()@pytest.mark.parametrize("host", ["10.0.0.8", "8.8.8.8", "127.0.0.1", "169.254.169.254", "100.64.0.1"])@@ -1059,3 +1061,117 @@ def test_api_key_scheme_survives_persistence_and_builds_auth(a2a_receiver, locatassert client.post(path, json=payload).status_code == 200restored = client.portal.call(lambda: stored.get(template_id="a2a-weather"))assert restored["agent_card"] == card++[email protected]("transport", ["ws", "http"])+async def test_user_switch_isolated_through_web_find_and_dispatch(monkeypatch, transport):+ from types import SimpleNamespace+ from jiuwenswarm.gateway.a2a_manager import A2AManager+ from jiuwenswarm.gateway.channel_manager.web.app_web_handlers import (+ WebHandlersBindParams, _register_web_handlers,+ )+ 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++ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")+ store = InMemoryPersistentBackend()+ repos = create_enterprise_record_repositories(store)+ await repos["a2a_outbound_template"].create(_projection_record())+ await repos["a2a_outbound_user_state"].create({+ "template_id": "a2a-weather", "user_id": None, "user_enabled": False,+ })+ await repos["a2a_access_policy_template"].create({+ "policy_id": "policy", "enabled": True, "mode": "allowlist",+ "member_template_ids": ["a2a-weather"],+ })+ await repos["agent_template"].create({+ "template_id": "template", "enabled": True,+ "template_ref": {"a2a_access_policy": ["policy"]},+ })+ await repos["instance_agent_resource"].create({+ "resource_id": "bot", "enabled": True, "ref_template_id": "template",+ })++ def projection():+ return EnterpriseA2AProjection(+ store, templates=repos["a2a_outbound_template"],+ user_states=repos["a2a_outbound_user_state"],+ runtime_states=repos["a2a_outbound_runtime_state"],+ policies=repos["a2a_access_policy_template"],+ agent_templates=repos["agent_template"],+ instance_resources=repos["instance_agent_resource"],+ )++ async def build_client(agent, credential):+ return _CompletedClient()++ manager = object.__new__(A2AManager)+ manager._outbound = A2AOutboundRegistry(projection())+ manager._outbound_dispatcher = A2AOutboundDispatcher(projection(), client_builder=build_client)++ class Channel:+ ws = WebWsTransport++ def __init__(self):+ self.methods = {}+ self.responses = []++ def register_method(self, name, handler):+ self.methods[name] = handler++ def on_connect(self, handler):+ pass++ async def send_response(self, ws, req_id, **response):+ self.responses.append(response)++ channel = Channel()+ 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):+ 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]++ async def enabled(user):+ response = await invoke("a2a.outbound.list", user)+ assert response["ok"]+ return response["payload"]["items"][0]["user_enabled"]++ assert await enabled("alice") is True # Unowned legacy false is ignored.+ assert (await invoke("a2a.outbound.enabled.update", "alice", agent_id="a2a-weather", user_enabled=False))["ok"]+ assert await enabled("alice") is False+ assert await enabled("bob") is True # Payload identity cannot modify Bob's state.+ assert (await invoke("a2a.outbound.enabled.update", "bob", agent_id="a2a-weather", user_enabled=True))["ok"]+ manager._outbound = A2AOutboundRegistry(projection()) # Reload persisted preferences.+ assert await enabled("alice") is False+ assert await enabled("bob") is True++ assert (await manager.outbound_find_agents(source_resource_id="bot", source_user_id="alice"))["total"] == 0+ assert (await manager.outbound_find_agents(source_resource_id="bot", source_user_id="bob"))["total"] == 1+ params = dict(agent_id="a2a-weather", task="weather", mode="sync", source_session_id="session", source_resource_id="bot")+ with pytest.raises(A2AOutboundError) as caught:+ await manager.outbound_dispatch_task(**params, source_user_id="alice")+ assert caught.value.code is A2AOutboundErrorCode.AGENT_USER_DISABLED+ with pytest.raises(A2AOutboundError):+ await manager._outbound_dispatcher.dispatch(**params, source_user_id="alice")+ assert (await manager.outbound_dispatch_task(**params, source_user_id="bob"))["status"] == "completed"++ for method in ("a2a.outbound.list", "a2a.outbound.enabled.update"):+ response = await invoke(method, None, agent_id="a2a-weather", user_enabled=True)+ assert response["code"] == "A2A_USER_IDENTITY_REQUIRED"+ with pytest.raises(A2AOutboundError) as caught:+ await manager.outbound_find_agents(source_resource_id="bot")+ assert caught.value.code is A2AOutboundErrorCode.USER_IDENTITY_REQUIRED+ await projection().clear_agent_state("a2a-weather")+ assert await repos["a2a_outbound_user_state"].list() == []diff --git a/tests/unit_tests/gateway/test_runtime_routed_client.py b/tests/unit_tests/gateway/test_runtime_routed_client.pyindex 067bf04b02..07f385b9bc 100644--- a/tests/unit_tests/gateway/test_runtime_routed_client.py+++ b/tests/unit_tests/gateway/test_runtime_routed_client.py@@ -148,6 +148,7 @@ async def test_reverse_rpc_over_real_http_sse(monkeypatch, stream):assert kwargs["query"] == "weather"if stream:assert kwargs["source_resource_id"] == "bot-1"+ assert kwargs["source_user_id"] == "user-1"return {"items": [{"agent_id": "weather"}], "total": 1}async def outbound_dispatch_task(self, **kwargs):@@ -177,7 +178,7 @@ async def test_reverse_rpc_over_real_http_sse(monkeypatch, stream):client = RuntimeRoutedAgentClient(route_client=route)handler = object.__new__(MessageHandler)handler._stream_sessions = {"req-1": "sess-1"}- handler._stream_metadata = {"req-1": {"routing": {"bot_id": "bot-1"}}}+ handler._stream_metadata = {"req-1": {"user_id": "user-1", "routing": {"bot_id": "bot-1"}}}handler._stream_channels = {"req-1": "web"}handler.set_a2a_outbound_tool_manager(Manager())