Skip to content

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

feat(a2a): outbound dispatch history, team rail integration and reverse-RPC hardening (batch 5+6/7)

NickFuryXXXb8a75a2a9050
diff --git a/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py b/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py
index 162593a15d..e265e5246d 100644
--- a/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/a2a_outbound_tools.py
@@ -20,9 +20,6 @@ from jiuwenswarm.gateway.a2a_manager.tool_rpc import (
from .acp_output_tools import get_acp_output_manager
-_RPC_DISPATCH_TIMEOUT_SECONDS = 360.0
-_RPC_QUERY_TIMEOUT_SECONDS = 15.0
-
class A2AOutboundToolBackend(Protocol):
@property
@@ -49,7 +46,7 @@ class GatewayA2AOutboundToolBackend:
return bool(
callable(getattr(get_acp_output_manager(), "_send_push_callback", None))
- and get_push_registry().subscriber_count() > 0
+ and get_push_registry().reverse_rpc_ready()
)
async def call(
@@ -68,13 +65,11 @@ class GatewayA2AOutboundToolBackend:
params,
session_id=session_id,
channel_id=channel_id,
- timeout=(
- _RPC_DISPATCH_TIMEOUT_SECONDS
- if method == _RPC_DISPATCH
- else _RPC_QUERY_TIMEOUT_SECONDS
- ),
+ # The Gateway Manager owns operation budgets. In particular,
+ # sync_wait_seconds must not be preempted by a transport timer.
+ timeout=None,
log_params=False,
- cancel_method=(_RPC_CANCEL if method == _RPC_DISPATCH else None),
+ cancel_method=_RPC_CANCEL,
)
except (asyncio.TimeoutError, RuntimeError):
return _error(A2AOutboundErrorCode.MANAGER_UNAVAILABLE)
diff --git a/jiuwenswarm/agents/harness/common/tools/acp_output_tools.py b/jiuwenswarm/agents/harness/common/tools/acp_output_tools.py
index 4d2c2855ac..bbd061edb7 100644
--- a/jiuwenswarm/agents/harness/common/tools/acp_output_tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/acp_output_tools.py
@@ -80,6 +80,14 @@ class AcpOutputManager:
"""
self._pending.clear()
+ def fail_pending_requests(self, exc: BaseException) -> None:
+ """Fail all requests owned by a reverse-RPC connection that was lost."""
+ pending = list(self._pending.values())
+ self._pending.clear()
+ for request in pending:
+ if not request.future.done():
+ request.future.set_exception(exc)
+
def add_pending_request(self, request: AcpOutputRequest) -> None:
"""Register a pending request explicitly.
@@ -141,12 +149,12 @@ class AcpOutputManager:
*,
channel_id: str = "acp",
session_id: str | None = None,
- timeout: float = _ACP_REQUEST_TIMEOUT_SECONDS,
+ timeout: float | None = _ACP_REQUEST_TIMEOUT_SECONDS,
log_params: bool = True,
cancel_method: str | None = None,
) -> dict[str, Any]:
loop = asyncio.get_running_loop()
- deadline = loop.time() + timeout
+ deadline = loop.time() + timeout if timeout is not None else None
logger.info(
"[AcpOutput] send_jsonrpc_request called: method=%s params=%s",
method,
@@ -216,10 +224,13 @@ class AcpOutputManager:
try:
callback_result = self._send_push_callback(push_msg)
if inspect.isawaitable(callback_result):
- callback_result = await asyncio.wait_for(
- callback_result,
- timeout=max(0.0, deadline - loop.time()),
- )
+ if deadline is None:
+ callback_result = await callback_result
+ else:
+ callback_result = await asyncio.wait_for(
+ callback_result,
+ timeout=max(0.0, deadline - loop.time()),
+ )
if callback_result is False or (
isinstance(callback_result, int) and callback_result <= 0
):
@@ -260,6 +271,8 @@ class AcpOutputManager:
try:
if future.done():
result = future.result()
+ elif deadline is None:
+ result = await future
else:
result = await asyncio.wait_for(
future,
@@ -280,7 +293,7 @@ class AcpOutputManager:
"[AcpOutput] request timed out: jsonrpc_id=%s method=%s timeout=%.1fs",
jsonrpc_id,
method,
- timeout,
+ float(timeout or 0),
)
raise
diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.py
index 4b6543af16..39280968bc 100644
--- a/jiuwenswarm/agents/swarm/config_specs.py
+++ b/jiuwenswarm/agents/swarm/config_specs.py
@@ -100,6 +100,7 @@ _COMMON_RAIL_NAMES: tuple[str, ...] = (
registry.PLUGIN_RAILS,
registry.SKILL_RETRIEVAL_PROMPT,
registry.SYMPHONY_ORCHESTRATION_PROMPT,
+ registry.A2A_OUTBOUND_TOOLKIT,
registry.DISABLED_TOOLS,
)
@@ -147,6 +148,7 @@ _CODE_RAIL_NAMES: tuple[str, ...] = (
registry.CODE_SKILL_USE,
registry.SKILL_RETRIEVAL_PROMPT,
registry.SYMPHONY_ORCHESTRATION_PROMPT,
+ registry.A2A_OUTBOUND_TOOLKIT,
registry.DISABLED_TOOLS,
)
diff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.py
index 9a80b3e1c1..4343a6c179 100644
--- a/jiuwenswarm/agents/swarm/providers/member_rails.py
+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py
@@ -39,6 +39,9 @@ from jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import (
from jiuwenswarm.agents.harness.common.rails.disabled_tools_rail import (
DisabledToolsRail,
)
+from jiuwenswarm.agents.harness.common.rails.a2a_outbound_toolkit_rail import (
+ A2AOutboundToolkitRail,
+)
from jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail import (
SkillRetrievalPromptRail,
)
@@ -69,6 +72,7 @@ CONTEXT_PROCESSOR = "swarm.context_processor"
PLUGIN_RAILS = "swarm.plugin_rails"
SKILL_RETRIEVAL_PROMPT = "swarm.skill_retrieval_prompt"
SYMPHONY_ORCHESTRATION_PROMPT = "swarm.symphony_orchestration_prompt"
+A2A_OUTBOUND_TOOLKIT = "swarm.a2a_outbound_toolkit"
TEAM_PERMISSION_POLICY = "swarm.team_permission_policy"
DISABLED_TOOLS = "swarm.disabled_tools"
@@ -150,6 +154,55 @@ def _build_symphony_orchestration_rail(
return SymphonyOrchestrationRail()
+class A2AOutboundToolkitInput(ConstructionInput):
+ """Stable Gateway route for a Team member's outbound A2A calls."""
+
+ session_id: str = context_field(
+ attr="session_id",
+ default="",
+ description="Originating Team session id.",
+ )
+ channel: str = context_field(
+ attr="channel",
+ default="default",
+ description="Resolved Gateway channel key.",
+ )
+
+
+@harness_element(
+ kind=ElementKind.RAIL,
+ name=A2A_OUTBOUND_TOOLKIT,
+ description="Exposes the registered external A2A Agent toolkit to Team members.",
+ input_model=A2AOutboundToolkitInput,
+)
+def _build_a2a_outbound_toolkit_rail(
+ params: dict[str, Any],
+ context: SwarmBuildContext,
+) -> A2AOutboundToolkitRail | None:
+ """Build the shared A2A rail with a route stable across member tasks."""
+ from jiuwenswarm.common.local_env_config import is_enterprise
+
+ if is_enterprise():
+ return None
+ inp = A2AOutboundToolkitInput.resolve(params, context)
+ session_id = str(inp.session_id or "").strip()
+ channel = str(inp.channel or "default").strip() or "default"
+
+ def _runtime_route() -> tuple[str, str]:
+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ get_runtime_tool_channel_id,
+ get_runtime_tool_session_id,
+ )
+
+ live_session = str(get_runtime_tool_session_id() or "").strip()
+ if live_session:
+ live_channel = str(get_runtime_tool_channel_id() or "").strip()
+ return live_session, live_channel or channel
+ return session_id, channel
+
+ return A2AOutboundToolkitRail(runtime_route=_runtime_route)
+
+
class DisabledToolsInput(ConstructionInput):
"""Configured tool names hidden from this swarm member."""
@@ -482,6 +535,7 @@ __all__ = [
"PLUGIN_RAILS",
"SKILL_RETRIEVAL_PROMPT",
"SYMPHONY_ORCHESTRATION_PROMPT",
+ "A2A_OUTBOUND_TOOLKIT",
"DISABLED_TOOLS",
"TEAM_PERMISSION",
"TEAM_PERMISSION_POLICY",
diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.py
index 2cdee0b0e2..5833d5946c 100644
--- a/jiuwenswarm/agents/swarm/registry.py
+++ b/jiuwenswarm/agents/swarm/registry.py
@@ -80,6 +80,7 @@ CONTEXT_PROCESSOR = _member_rails.CONTEXT_PROCESSOR
PLUGIN_RAILS = _member_rails.PLUGIN_RAILS
SKILL_RETRIEVAL_PROMPT = _member_rails.SKILL_RETRIEVAL_PROMPT
SYMPHONY_ORCHESTRATION_PROMPT = _member_rails.SYMPHONY_ORCHESTRATION_PROMPT
+A2A_OUTBOUND_TOOLKIT = _member_rails.A2A_OUTBOUND_TOOLKIT
DISABLED_TOOLS = _member_rails.DISABLED_TOOLS
TEAM_PERMISSION = _member_rails.TEAM_PERMISSION
TEAM_PERMISSION_POLICY = _member_rails.TEAM_PERMISSION_POLICY
@@ -190,6 +191,7 @@ __all__ = [
"PLUGIN_RAILS",
"SKILL_RETRIEVAL_PROMPT",
"SYMPHONY_ORCHESTRATION_PROMPT",
+ "A2A_OUTBOUND_TOOLKIT",
"DISABLED_TOOLS",
"TEAM_PERMISSION",
"TEAM_PERMISSION_POLICY",
diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx
index 6e6f44dab0..4c14f8de41 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/A2AOutboundPanel.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
-import { ChevronDown } from 'lucide-react';
+import { ChevronDown, Plus, Power, RefreshCw, Search, Server, Trash2, X } from 'lucide-react';
import type { WebError } from '../../types/websocket';
import { Switch } from '../Switch';
import {
@@ -17,19 +18,23 @@ import {
interface Props {
isConnected: boolean;
request: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>;
+ headerActionsContainer?: HTMLElement | null;
}
const BADGE: Record<A2AOutboundAvailability, string> = {
- available: 'bg-ok/15 text-ok', unreachable: 'bg-danger/15 text-danger',
- incompatible: 'bg-danger/15 text-danger', review_required: 'bg-warn/15 text-warn',
+ available: 'bg-ok/15 text-ok',
+ unreachable: 'bg-danger/15 text-danger',
+ incompatible: 'bg-danger/15 text-danger',
+ review_required: 'bg-warn/15 text-warn',
};
const errorMessage = (error: unknown): string => (error as WebError)?.message || String(error);
-export function A2AOutboundPanel({ isConnected, request }: Props) {
+export function A2AOutboundPanel({ isConnected, request, headerActionsContainer }: Props) {
const { t, i18n } = useTranslation();
const [url, setUrl] = useState('');
const [discovery, setDiscovery] = useState<A2AOutboundDiscovery | null>(null);
+ const [discoveryDrawerOpen, setDiscoveryDrawerOpen] = useState(false);
const [agents, setAgents] = useState<A2AOutboundAgent[]>([]);
const [allowLoopbackHttp, setAllowLoopbackHttp] = useState(false);
const [savedAllowLoopbackHttp, setSavedAllowLoopbackHttp] = useState(false);
@@ -39,17 +44,21 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
- const [editing, setEditing] = useState<{ agentId: string; displayName: string; connectTimeout: string; syncWait: string; credential: string; clearCredential: boolean } | null>(null);
+ const [editing, setEditing] = useState<{
+ agentId: string;
+ displayName: string;
+ connectTimeout: string;
+ syncWait: string;
+ credential: string;
+ clearCredential: boolean;
+ } | null>(null);
const generationRef = useRef(0);
const refresh = useCallback(async () => {
if (!isConnected) return;
const generation = ++generationRef.current;
try {
- const [payload, rawSettings] = await Promise.all([
- request('a2a.outbound.list'),
- request('a2a.outbound.settings.get'),
- ]);
+ const [payload, rawSettings] = await Promise.all([request('a2a.outbound.list'), request('a2a.outbound.settings.get')]);
if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;
const next = normalizeA2AOutboundList(payload);
const settings = normalizeA2AOutboundSettings(rawSettings);
@@ -63,18 +72,49 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {
}
}, [isConnected, request, t]);
- useEffect(() => { void refresh(); }, [refresh]);
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ const closeDiscoveryDrawer = useCallback(() => {
+ if (busy) return;
+ setDiscoveryDrawerOpen(false);
+ setDiscovery(null);
+ setUrl('');
+ setDisplayName('');
+ setCredential('');
+ setAdvancedOpen(false);
+ setError(null);
+ setNotice(null);
+ }, [busy]);
+
+ useEffect(() => {
+ if (!discoveryDrawerOpen) return;
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') closeDiscoveryDrawer();
+ };
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [closeDiscoveryDrawer, discoveryDrawerOpen]);
const discover = async () => {
if (!url.trim() || busy || !isConnected) return;
- setBusy('discover'); setError(null); setNotice(null); setDiscovery(null);
+ setBusy('discover');
+ setError(null);
+ setNotice(null);
+ setDiscovery(null);
try {
const next = normalizeA2AOutboundDiscovery(await request('a2a.outbound.discover', { url: url.trim() }));
if (!next) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));
- setDiscovery(next); setDisplayName(next.agent.name); setCredential('');
+ setDiscovery(next);
+ setDisplayName(next.agent.name);
+ setCredential('');
setNotice(t('a2aIngress.outbound.discovery.previewReady'));
- } catch (nextError) { setError(errorMessage(nextError)); }
- finally { setBusy(null); }
+ } catch (nextError) {
+ setError(errorMessage(nextError));
+ } finally {
+ setBusy(null);
+ }
};
const updateAllowLoopbackHttp = async (nextEnabled: boolean) => {
@@ -82,11 +122,15 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {
const generation = ++generationRef.current;
const previous = savedAllowLoopbackHttp;
setAllowLoopbackHttp(nextEnabled);
- setBusy('settings'); setError(null); setNotice(null);
+ setBusy('settings');
+ setError(null);
+ setNotice(null);
try {
- const settings = normalizeA2AOutboundSettings(await request('a2a.outbound.settings.update', {
- allow_loopback_http: nextEnabled,
- }));
+ const settings = normalizeA2AOutboundSettings(
+ await request('a2a.outbound.settings.update', {
+ allow_loopback_http: nextEnabled,
+ }),
+ );
if (!settings) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));
if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;
setAllowLoopbackHttp(settings.allow_loopback_http);
@@ -96,44 +140,65 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {
if (!shouldAcceptA2AOutboundResponse(generation, generationRef.current)) return;
setAllowLoopbackHttp(previous);
setError(errorMessage(nextError));
+ } finally {
+ setBusy(null);
}
- finally { setBusy(null); }
};
const register = async () => {
if (!discovery || busy || !isConnected) return;
- setBusy('register'); setError(null);
+ setBusy('register');
+ setError(null);
try {
const payload = await request('a2a.outbound.register', {
- discovery_id: discovery.discovery_id, display_name: displayName.trim() || discovery.agent.name,
- enabled: true, ...(credential ? { credential } : {}),
+ discovery_id: discovery.discovery_id,
+ display_name: displayName.trim() || discovery.agent.name,
+ enabled: true,
+ ...(credential ? { credential } : {}),
});
const created = normalizeA2AOutboundAgent(payload);
if (!created) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));
- generationRef.current += 1; setAgents(current => [created, ...current]); setDiscovery(null); setCredential('');
+ generationRef.current += 1;
+ setAgents(current => [created, ...current]);
+ setDiscovery(null);
+ setCredential('');
+ setDiscoveryDrawerOpen(false);
+ setUrl('');
+ setAdvancedOpen(false);
setNotice(t('a2aIngress.outbound.registered'));
- } catch (nextError) { setError(errorMessage(nextError)); }
- finally { setBusy(null); }
+ } catch (nextError) {
+ setError(errorMessage(nextError));
+ } finally {
+ setBusy(null);
+ }
};
const operate = async (agent: A2AOutboundAgent, operation: 'toggle' | 'refresh' | 'confirm' | 'reject' | 'delete') => {
if (busy || !isConnected) return;
if (operation === 'delete' && !window.confirm(t('a2aIngress.outbound.deleteConfirm'))) return;
- setBusy(`${operation}:${agent.agent_id}`); setError(null); setNotice(null); generationRef.current += 1;
+ setBusy(`${operation}:${agent.agent_id}`);
+ setError(null);
+ setNotice(null);
+ generationRef.current += 1;
try {
let payload: unknown;
if (operation === 'toggle') payload = await request('a2a.outbound.update', { agent_id: agent.agent_id, enabled: !agent.enabled });
else if (operation === 'refresh') payload = await request('a2a.outbound.refresh', { agent_id: agent.agent_id });
- else if (operation === 'confirm' || operation === 'reject') payload = await request('a2a.outbound.confirm_revision', { agent_id: agent.agent_id, accept: operation === 'confirm' });
+ else 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 (operation === 'delete') setAgents(current => current.filter(item => item.agent_id !== agent.agent_id));
else {
const updated = normalizeA2AOutboundAgent(payload);
if (!updated) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));
- setAgents(current => current.map(item => item.agent_id === updated.agent_id ? updated : item));
+ setAgents(current => current.map(item => (item.agent_id === updated.agent_id ? updated : item)));
}
- } catch (nextError) { setError(errorMessage(nextError)); void refresh(); }
- finally { setBusy(null); }
+ } catch (nextError) {
+ setError(errorMessage(nextError));
+ void refresh();
+ } finally {
+ setBusy(null);
+ }
};
const saveSettings = async (agent: A2AOutboundAgent) => {
@@ -141,83 +206,456 @@ export function A2AOutboundPanel({ isConnected, request }: Props) {
const connectTimeout = Number(editing.connectTimeout);
const syncWait = Number(editing.syncWait);
if (!editing.displayName.trim() || !Number.isFinite(connectTimeout) || connectTimeout <= 0 || !Number.isFinite(syncWait) || syncWait <= 0) {
- setError(t('a2aIngress.outbound.errors.invalidSettings')); return;
+ setError(t('a2aIngress.outbound.errors.invalidSettings'));
+ return;
}
- setBusy(`save:${agent.agent_id}`); setError(null); generationRef.current += 1;
+ setBusy(`save:${agent.agent_id}`);
+ setError(null);
+ generationRef.current += 1;
try {
const payload = await request('a2a.outbound.update', {
- agent_id: agent.agent_id, display_name: editing.displayName.trim(),
- connect_timeout_seconds: connectTimeout, sync_wait_seconds: syncWait,
+ agent_id: agent.agent_id,
+ display_name: editing.displayName.trim(),
+ connect_timeout_seconds: connectTimeout,
+ sync_wait_seconds: syncWait,
...(editing.credential ? { credential: editing.credential } : {}),
...(editing.clearCredential ? { clear_credential: true } : {}),
});
const updated = normalizeA2AOutboundAgent(payload);
if (!updated) throw new Error(t('a2aIngress.outbound.errors.invalidResponse'));
- setAgents(current => current.map(item => item.agent_id === updated.agent_id ? updated : item));
- setEditing(null); setNotice(t('a2aIngress.outbound.saved'));
- } catch (nextError) { setError(errorMessage(nextError)); void refresh(); }
- finally { setBusy(null); }
+ setAgents(current => current.map(item => (item.agent_id === updated.agent_id ? updated : item)));
+ setEditing(null);
+ setNotice(t('a2aIngress.outbound.saved'));
+ } catch (nextError) {
+ setError(errorMessage(nextError));
+ void refresh();
+ } finally {
+ setBusy(null);
+ }
};
- return <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-auto pr-1 pt-1">
- {!isConnected && <Notice tone="warn">{t('a2aIngress.disconnected')}</Notice>}
- {error && <Notice tone="danger">{error}</Notice>}
- {notice && <Notice tone="ok">{notice}</Notice>}
- <section className="rounded-xl border border-border bg-panel-strong/60 p-4">
- <h3 className="text-sm font-semibold text-text">{t('a2aIngress.outbound.discovery.title')}</h3>
- <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.discovery.description')}</p>
- <div className="mt-4 flex gap-2">
- <input className="min-w-0 flex-1 rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent" value={url} onChange={event => setUrl(event.target.value)} placeholder="https://agent.example.com" disabled={!!busy} />
- <button type="button" className="btn primary" onClick={() => void discover()} disabled={!isConnected || !!busy || !url.trim()}>{busy === 'discover' ? t('a2aIngress.outbound.discovery.discovering') : t('a2aIngress.outbound.discovery.action')}</button>
- </div>
- <div className="mt-4 border-t border-border pt-3">
+ const toggleSettings = (agent: A2AOutboundAgent) => {
+ setEditing(current =>
+ current?.agentId === agent.agent_id
+ ? null
+ : {
+ agentId: agent.agent_id,
+ displayName: agent.display_name,
+ connectTimeout: String(agent.connect_timeout_seconds),
+ syncWait: String(agent.sync_wait_seconds),
+ credential: '',
+ clearCredential: false,
+ },
+ );
+ };
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-4 pr-1">
+ {headerActionsContainer &&
+ createPortal(
+ <button
+ type="button"
+ className="btn primary"
+ onClick={() => {
+ setError(null);
+ setNotice(null);
+ setDiscoveryDrawerOpen(true);
+ }}
+ disabled={!isConnected || !!busy}
+ >
+ <Plus size={16} />
+ {t('a2aIngress.outbound.discovery.action')}
+ </button>,
+ headerActionsContainer,
+ )}
+ {!isConnected && <Notice tone="warn">{t('a2aIngress.disconnected')}</Notice>}
+ {!discoveryDrawerOpen && error && (
+ <Notice tone="danger" onClose={() => setError(null)} closeLabel={t('common.close')}>
+ {error}
+ </Notice>
+ )}
+ {!discoveryDrawerOpen && notice && (
+ <Notice tone="ok" onClose={() => setNotice(null)} closeLabel={t('common.close')}>
+ {notice}
+ </Notice>
+ )}
+
+ {discoveryDrawerOpen && (
+ <div className="fixed inset-0 z-[1400] flex justify-end bg-overlay-cron-drawer" onClick={closeDiscoveryDrawer}>
+ <section
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="a2a-discovery-drawer-title"
+ className="relative flex h-full w-[640px] max-w-full flex-col bg-card shadow-xl animate-slide-in-right"
+ onClick={event => event.stopPropagation()}
+ >
+ <div className="flex shrink-0 items-start justify-between gap-4 border-b border-border px-5 py-4">
+ <div className="min-w-0">
+ <h3 id="a2a-discovery-drawer-title" className="text-xl font-bold text-text-strong">
+ {t('a2aIngress.outbound.discovery.title')}
+ </h3>
+ <p className="mt-1 text-sm text-text-muted">{t('a2aIngress.outbound.discovery.description')}</p>
+ </div>
+ <button
+ type="button"
+ className="grid h-9 w-9 shrink-0 place-items-center rounded-lg text-text-muted hover:bg-secondary/50 hover:text-text"
+ onClick={closeDiscoveryDrawer}
+ disabled={!!busy}
+ aria-label={t('common.close')}
+ >
+ <X size={20} />
+ </button>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto bg-secondary/10 p-5">
+ <div className="grid gap-4">
+ <section className="rounded-xl border border-border bg-card p-4">
+ <label className="text-xs font-medium text-text-muted" htmlFor="a2a-agent-card-url">
+ {t('a2aIngress.outbound.discovery.urlLabel')}
+ </label>
+ <div className="mt-2 flex flex-col gap-2 sm:flex-row">
+ <input
+ id="a2a-agent-card-url"
+ className="min-w-0 flex-1 rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
+ value={url}
+ onChange={event => setUrl(event.target.value)}
+ placeholder="https://agent.example.com/.well-known/agent-card.json"
+ disabled={!!busy}
+ />
+ <button type="button" className="btn primary shrink-0" onClick={() => void discover()} disabled={!isConnected || !!busy || !url.trim()}>
+ <Search size={16} />
+ {busy === 'discover' ? t('a2aIngress.outbound.discovery.discovering') : t('a2aIngress.outbound.discovery.action')}
+ </button>
+ </div>
+ <div className="mt-4 border-t border-border pt-3">
+ <button
+ type="button"
+ className="flex w-full items-center justify-between gap-3 text-left text-sm font-medium text-text-muted hover:text-text"
+ aria-expanded={advancedOpen}
+ onClick={() => setAdvancedOpen(open => !open)}
+ >
+ <span>{t('a2aIngress.outbound.discovery.advanced')}</span>
+ <ChevronDown size={16} className={`shrink-0 transition-transform ${advancedOpen ? 'rotate-180' : ''}`} />
+ </button>
+ {advancedOpen && (
+ <div className="mt-3 rounded-lg bg-secondary/30 p-3">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium text-text">{t('a2aIngress.outbound.localDebug.allow')}</div>
+ <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.localDebug.description')}</p>
+ </div>
+ <Switch
+ checked={allowLoopbackHttp}
+ onChange={nextEnabled => void updateAllowLoopbackHttp(nextEnabled)}
+ disabled={!isConnected || !!busy}
+ title={t('a2aIngress.outbound.localDebug.allow')}
+ />
+ </div>
+ {allowLoopbackHttp && (
+ <p className="mt-3 border-t border-warn/20 pt-3 text-xs text-warn">{t('a2aIngress.outbound.localDebug.warning')}</p>
+ )}
+ </div>
+ )}
+ </div>
+ </section>
+
+ {(error || notice) && (
+ <div className="grid gap-3">
+ {error && (
+ <Notice tone="danger" onClose={() => setError(null)} closeLabel={t('common.close')}>
+ {error}
+ </Notice>
+ )}
+ {notice && (
+ <Notice tone="ok" onClose={() => setNotice(null)} closeLabel={t('common.close')}>
+ {notice}
+ </Notice>
+ )}
+ </div>
+ )}
+
+ {discovery && (
+ <section className="grid gap-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h4 className="text-sm font-semibold text-text">{t('a2aIngress.outbound.discovery.candidateTitle')}</h4>
+ <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.discovery.candidateDescription')}</p>
+ </div>
+ <span className="rounded-full border border-border bg-card px-2.5 py-1 text-xs text-text-muted">
+ {t('a2aIngress.outbound.discovery.previewOnly')}
+ </span>
+ </div>
+ <div className="grid gap-4">
+ <div className="rounded-xl border border-border bg-card p-4">
+ <div className="flex items-start gap-3">
+ <div className="grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-accent/10 text-accent">
+ <Server size={20} />
+ </div>
+ <div className="min-w-0">
+ <h5 className="font-semibold text-text">{discovery.agent.name}</h5>
+ <p className="mt-1 text-sm leading-5 text-text-muted">{discovery.agent.description || '-'}</p>
+ </div>
+ </div>
+ <div className="mt-4 grid gap-3 rounded-lg bg-secondary/30 p-3 sm:grid-cols-2">
+ <Value label={t('a2aIngress.outbound.fields.version')} value={discovery.agent.version || '-'} />
+ <Value
+ label={t('a2aIngress.outbound.fields.protocol')}
+ value={`${discovery.agent.compatible_interfaces[0].protocol_binding} ${discovery.agent.compatible_interfaces[0].protocol_version}`}
+ />
+ <Value label={t('a2aIngress.outbound.fields.endpoint')} value={discovery.agent.compatible_interfaces[0].url} mono />
+ <Value label={t('a2aIngress.outbound.fields.expiresAt')} value={formatTime(discovery.expires_at, i18n.language)} />
+ </div>
+ </div>
+ <div className="rounded-xl border border-border bg-card p-4">
+ <h5 className="text-sm font-semibold text-text">{t('a2aIngress.outbound.discovery.registrationTitle')}</h5>
+ <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.discovery.registrationDescription')}</p>
+ <div className="mt-4 grid gap-3 sm:grid-cols-2">
+ <Input label={t('a2aIngress.outbound.fields.displayName')} value={displayName} onChange={setDisplayName} />
+ <Input label={t('a2aIngress.outbound.fields.credential')} value={credential} onChange={setCredential} type="password" />
+ </div>
+ <div className="mt-4 flex justify-end gap-2 border-t border-border pt-4">
+ <button type="button" className="btn secondary" onClick={() => setDiscovery(null)} disabled={!!busy}>
+ {t('common.cancel')}
+ </button>
+ <button type="button" className="btn primary" onClick={() => void register()} disabled={!!busy}>
+ {busy === 'register' ? t('a2aIngress.outbound.registering') : t('a2aIngress.outbound.register')}
+ </button>
+ </div>
+ </div>
+ </div>
+ </section>
+ )}
+ </div>
+ </div>
+ </section>
+ </div>
+ )}
+
+ <section className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-panel-strong/60">
+ <div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3">
+ <div>
+ <div className="flex items-center gap-2">
+ <h3 className="text-sm font-semibold text-text">{t('a2aIngress.outbound.list.title')}</h3>
+ <span className="rounded-full bg-secondary px-2 py-0.5 text-xs text-text-muted">{agents.length}</span>
+ </div>
+ <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.list.description')}</p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" className="btn secondary" onClick={() => void refresh()} disabled={!isConnected || !!busy}>
+ <RefreshCw size={16} />
+ {t('common.refresh')}
+ </button>
+ </div>
+ </div>
+ {agents.length === 0 ? (
+ <div className="grid min-h-0 flex-1 place-items-center px-4 py-12 text-center text-sm text-text-muted">{t('a2aIngress.outbound.list.empty')}</div>
+ ) : (
+ <div className="grid min-h-0 flex-1 content-start gap-3 overflow-auto p-4">
+ {agents.map(agent => {
+ const isEditing = editing?.agentId === agent.agent_id;
+ const settingsPanelId = `a2a-agent-settings-${agent.agent_id}`;
+ return (
+ <article key={agent.agent_id} className="overflow-hidden rounded-xl border border-border bg-card shadow-sm">
+ <div className="p-4">
+ <div className="flex min-w-0 items-start gap-3">
+ <div className="grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-accent/10 text-accent">
+ <Server size={20} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <h4 className="text-base font-semibold text-text">{agent.display_name}</h4>
+ <span className={`rounded-full px-2 py-0.5 text-xs ${BADGE[agent.availability]}`}>
+ {t(`a2aIngress.outbound.availability.${agent.availability}`)}
+ </span>
+ <span className="rounded-full bg-secondary px-2 py-0.5 text-xs text-text-muted">
+ {agent.enabled ? t('a2aIngress.outbound.enabled') : t('a2aIngress.outbound.disabled')}
+ </span>
+ </div>
+ <div className="mt-1 break-all font-mono text-xs text-text-muted">{agent.selected_interface.url}</div>
+ </div>
+ </div>
+ <div className="mt-4 grid gap-3 rounded-lg border border-border bg-secondary/20 p-3 sm:grid-cols-2 xl:grid-cols-4">
+ <Value
+ label={t('a2aIngress.outbound.fields.protocol')}
+ value={`${agent.selected_interface.protocol_binding} ${agent.selected_interface.protocol_version}`}
+ />
+ <Value label={t('a2aIngress.outbound.fields.revision')} value={String(agent.card_revision)} />
+ <Value
+ label={t('a2aIngress.outbound.fields.credentialState')}
+ value={agent.has_credential ? t('a2aIngress.outbound.configured') : t('a2aIngress.outbound.notConfigured')}
+ />
+ <Value
+ label={t('a2aIngress.outbound.fields.lastChecked')}
+ value={agent.last_checked_at ? formatTime(agent.last_checked_at, i18n.language) : '-'}
+ />
+ </div>
+ {agent.last_error_summary && <p className="mt-3 rounded-md bg-danger/10 px-3 py-2 text-xs text-danger">{agent.last_error_summary}</p>}
+ <div className="mt-4 border-t border-border pt-3">
+ <button
+ type="button"
+ className="flex w-full items-center justify-between gap-3 text-left text-sm font-medium text-text-muted hover:text-text"
+ onClick={() => toggleSettings(agent)}
+ disabled={!!busy}
+ aria-expanded={isEditing}
+ aria-controls={settingsPanelId}
+ >
+ <span>{t('a2aIngress.outbound.settings')}</span>
+ <ChevronDown size={16} className={`shrink-0 transition-transform ${isEditing ? 'rotate-180' : ''}`} />
+ </button>
+ {isEditing && editing && (
+ <div id={settingsPanelId} className="mt-3 rounded-lg bg-secondary/30 p-3">
+ <div className="grid gap-3 md:grid-cols-2">
+ <Input
+ label={t('a2aIngress.outbound.fields.displayName')}
+ value={editing.displayName}
+ onChange={value => setEditing(current => (current ? { ...current, displayName: value } : current))}
+ />
+ <Input
+ label={t('a2aIngress.outbound.fields.connectTimeout')}
+ value={editing.connectTimeout}
+ onChange={value => setEditing(current => (current ? { ...current, connectTimeout: value } : current))}
+ />
+ <Input
+ label={t('a2aIngress.outbound.fields.syncWait')}
+ value={editing.syncWait}
+ onChange={value => setEditing(current => (current ? { ...current, syncWait: value } : current))}
+ />
+ <Input
+ label={t('a2aIngress.outbound.fields.replaceCredential')}
+ value={editing.credential}
+ onChange={value => setEditing(current => (current ? { ...current, credential: value, clearCredential: false } : current))}
+ type="password"
+ />
+ </div>
+ <label className="mt-3 flex items-center gap-2 text-sm text-text">
+ <input
+ type="checkbox"
+ checked={editing.clearCredential}
+ onChange={event =>
+ setEditing(current =>
+ current
+ ? { ...current, clearCredential: event.target.checked, credential: event.target.checked ? '' : current.credential }
+ : current,
+ )
+ }
+ />
+ {t('a2aIngress.outbound.clearCredential')}
+ </label>
+ <div className="mt-4 flex justify-end gap-2 border-t border-border pt-4">
+ <button type="button" className="btn secondary" onClick={() => setEditing(null)}>
+ {t('common.cancel')}
+ </button>
+ <button type="button" className="btn primary" onClick={() => void saveSettings(agent)} disabled={!!busy}>
+ {t('common.save')}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ {agent.availability === 'review_required' && (
+ <div className="mt-4 rounded-lg border border-warn/30 bg-warn/10 p-3 text-sm">
+ <p>{t('a2aIngress.outbound.reviewRequired')}</p>
+ <PendingDiff agent={agent} label={t('a2aIngress.outbound.endpointChange')} />
+ <div className="mt-3 flex gap-2">
+ <button type="button" className="btn primary" onClick={() => void operate(agent, 'confirm')} disabled={!!busy}>
+ {t('a2aIngress.outbound.confirm')}
+ </button>
+ <button type="button" className="btn secondary" onClick={() => void operate(agent, 'reject')} disabled={!!busy}>
+ {t('a2aIngress.outbound.reject')}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="flex flex-wrap justify-end gap-2 border-t border-border bg-secondary/10 px-4 py-3">
+ <button
+ type="button"
+ className="btn secondary"
+ onClick={() => void operate(agent, 'toggle')}
+ disabled={!!busy || agent.availability === 'review_required'}
+ >
+ <Power size={16} />
+ {agent.enabled ? t('a2aIngress.outbound.disable') : t('a2aIngress.outbound.enable')}
+ </button>
+ <button type="button" className="btn secondary" onClick={() => void operate(agent, 'refresh')} disabled={!!busy}>
+ <RefreshCw size={16} />
+ {t('a2aIngress.outbound.refresh')}
+ </button>
+ <button type="button" className="btn secondary text-danger" onClick={() => void operate(agent, 'delete')} disabled={!!busy}>
+ <Trash2 size={16} />
+ {t('common.delete')}
+ </button>
+ </div>
+ </article>
+ );
+ })}
+ </div>
+ )}
+ </section>
+ </div>
+ );
+}
+
+function formatTime(value: string, language: string): string {
+ return new Date(value).toLocaleString(language.startsWith('zh') ? 'zh-CN' : 'en-US', { hour12: false });
+}
+function Notice({
+ tone,
+ children,
+ onClose,
+ closeLabel,
+}: {
+ tone: 'warn' | 'danger' | 'ok';
+ children: React.ReactNode;
+ onClose?: () => void;
+ closeLabel?: string;
+}) {
+ const style = tone === 'danger' ? 'border-danger/30 bg-danger/10' : tone === 'warn' ? 'border-warn/30 bg-warn/10' : 'border-ok/30 bg-ok/10';
+ return (
+ <div className={`flex items-center justify-between gap-3 rounded-xl border px-4 py-3 text-sm text-text ${style}`} role={tone === 'danger' ? 'alert' : 'status'}>
+ <div className="min-w-0 flex-1 leading-5">{children}</div>
+ {onClose && (
<button
type="button"
- className="flex w-full items-center justify-between gap-3 text-left text-sm font-medium text-text-muted hover:text-text"
- aria-expanded={advancedOpen}
- onClick={() => setAdvancedOpen(open => !open)}
+ className="grid h-7 w-7 shrink-0 place-items-center rounded-md text-text-muted hover:bg-black/5 hover:text-text"
+ onClick={onClose}
+ aria-label={closeLabel}
>
- <span>{t('a2aIngress.outbound.discovery.advanced')}</span>
- <ChevronDown size={16} className={`shrink-0 transition-transform ${advancedOpen ? 'rotate-180' : ''}`} />
+ <X size={16} />
</button>
- {advancedOpen && <div className="mt-3 rounded-lg border border-border bg-bg/60 p-3">
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div className="min-w-0 flex-1">
- <div className="text-sm font-medium text-text">{t('a2aIngress.outbound.localDebug.allow')}</div>
- <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.localDebug.description')}</p>
- </div>
- <Switch
- checked={allowLoopbackHttp}
- onChange={nextEnabled => void updateAllowLoopbackHttp(nextEnabled)}
- disabled={!isConnected || !!busy}
- title={t('a2aIngress.outbound.localDebug.allow')}
- />
- </div>
- {allowLoopbackHttp && <p className="mt-3 border-t border-warn/20 pt-3 text-xs text-warn">{t('a2aIngress.outbound.localDebug.warning')}</p>}
- </div>}
- </div>
- </section>
- {discovery && <section className="rounded-xl border border-accent/30 bg-accent/5 p-4">
- <div className="flex flex-wrap items-start justify-between gap-3"><div><h3 className="font-semibold text-text">{discovery.agent.name}</h3><p className="mt-1 text-sm text-text-muted">{discovery.agent.description || '-'}</p></div><span className="rounded-full bg-secondary px-2.5 py-1 text-xs text-text-muted">{t('a2aIngress.outbound.discovery.previewOnly')}</span></div>
- <div className="mt-4 grid gap-3 text-xs md:grid-cols-2"><Value label={t('a2aIngress.outbound.fields.version')} value={discovery.agent.version || '-'} /><Value label={t('a2aIngress.outbound.fields.endpoint')} value={discovery.agent.compatible_interfaces[0].url} /><Value label={t('a2aIngress.outbound.fields.protocol')} value={`${discovery.agent.compatible_interfaces[0].protocol_binding} ${discovery.agent.compatible_interfaces[0].protocol_version}`} /><Value label={t('a2aIngress.outbound.fields.expiresAt')} value={formatTime(discovery.expires_at, i18n.language)} /></div>
- <div className="mt-4 grid gap-3 md:grid-cols-2"><Input label={t('a2aIngress.outbound.fields.displayName')} value={displayName} onChange={setDisplayName} /><Input label={t('a2aIngress.outbound.fields.credential')} value={credential} onChange={setCredential} type="password" /></div>
- <div className="mt-4 flex justify-end gap-2"><button type="button" className="btn secondary" onClick={() => setDiscovery(null)} disabled={!!busy}>{t('common.cancel')}</button><button type="button" className="btn primary" onClick={() => void register()} disabled={!!busy}>{busy === 'register' ? t('a2aIngress.outbound.registering') : t('a2aIngress.outbound.register')}</button></div>
- </section>}
- <section className="rounded-xl border border-border bg-panel-strong/60">
- <div className="flex items-center justify-between border-b border-border px-4 py-3"><div><h3 className="text-sm font-semibold text-text">{t('a2aIngress.outbound.list.title')}</h3><p className="mt-1 text-xs text-text-muted">{t('a2aIngress.outbound.list.total', { count: agents.length })}</p></div><button type="button" className="btn secondary" onClick={() => void refresh()} disabled={!isConnected || !!busy}>{t('common.refresh')}</button></div>
- {agents.length === 0 ? <div className="px-4 py-12 text-center text-sm text-text-muted">{t('a2aIngress.outbound.list.empty')}</div> : <div className="divide-y divide-border">{agents.map(agent => <div key={agent.agent_id} className="p-4">
- <div className="flex flex-wrap items-start justify-between gap-3"><div><div className="flex items-center gap-2"><span className="font-medium text-text">{agent.display_name}</span><span className={`rounded-full px-2 py-0.5 text-xs ${BADGE[agent.availability]}`}>{t(`a2aIngress.outbound.availability.${agent.availability}`)}</span><span className="rounded-full bg-secondary px-2 py-0.5 text-xs text-text-muted">{agent.enabled ? t('a2aIngress.outbound.enabled') : t('a2aIngress.outbound.disabled')}</span></div><div className="mt-2 break-all font-mono text-xs text-text-muted">{agent.selected_interface.url}</div></div><div className="flex flex-wrap gap-2"><button type="button" className="btn secondary" onClick={() => setEditing({ agentId: agent.agent_id, displayName: agent.display_name, connectTimeout: String(agent.connect_timeout_seconds), syncWait: String(agent.sync_wait_seconds), credential: '', clearCredential: false })} disabled={!!busy}>{t('a2aIngress.outbound.settings')}</button><button type="button" className="btn secondary" onClick={() => void operate(agent, 'toggle')} disabled={!!busy || agent.availability === 'review_required'}>{agent.enabled ? t('a2aIngress.outbound.disable') : t('a2aIngress.outbound.enable')}</button><button type="button" className="btn secondary" onClick={() => void operate(agent, 'refresh')} disabled={!!busy}>{t('a2aIngress.outbound.refresh')}</button><button type="button" className="btn secondary text-danger" onClick={() => void operate(agent, 'delete')} disabled={!!busy}>{t('common.delete')}</button></div></div>
- <div className="mt-3 flex flex-wrap gap-x-5 gap-y-1 text-xs text-text-muted"><span>{t('a2aIngress.outbound.fields.revision')}: {agent.card_revision}</span><span>{t('a2aIngress.outbound.fields.credentialState')}: {agent.has_credential ? t('a2aIngress.outbound.configured') : t('a2aIngress.outbound.notConfigured')}</span><span>{t('a2aIngress.outbound.fields.lastChecked')}: {agent.last_checked_at ? formatTime(agent.last_checked_at, i18n.language) : '-'}</span></div>
- {agent.last_error_summary && <p className="mt-2 text-xs text-danger">{agent.last_error_summary}</p>}
- {editing?.agentId === agent.agent_id && <div className="mt-3 rounded-lg border border-border bg-bg p-3"><div className="grid gap-3 md:grid-cols-2"><Input label={t('a2aIngress.outbound.fields.displayName')} value={editing.displayName} onChange={value => setEditing(current => current ? { ...current, displayName: value } : current)} /><Input label={t('a2aIngress.outbound.fields.connectTimeout')} value={editing.connectTimeout} onChange={value => setEditing(current => current ? { ...current, connectTimeout: value } : current)} /><Input label={t('a2aIngress.outbound.fields.syncWait')} value={editing.syncWait} onChange={value => setEditing(current => current ? { ...current, syncWait: value } : current)} /><Input label={t('a2aIngress.outbound.fields.replaceCredential')} value={editing.credential} onChange={value => setEditing(current => current ? { ...current, credential: value, clearCredential: false } : current)} type="password" /></div><label className="mt-3 flex items-center gap-2 text-sm text-text"><input type="checkbox" checked={editing.clearCredential} onChange={event => setEditing(current => current ? { ...current, clearCredential: event.target.checked, credential: event.target.checked ? '' : current.credential } : current)} />{t('a2aIngress.outbound.clearCredential')}</label><div className="mt-3 flex justify-end gap-2"><button type="button" className="btn secondary" onClick={() => setEditing(null)}>{t('common.cancel')}</button><button type="button" className="btn primary" onClick={() => void saveSettings(agent)} disabled={!!busy}>{t('common.save')}</button></div></div>}
- {agent.availability === 'review_required' && <div className="mt-3 rounded-lg border border-warn/30 bg-warn/10 p-3 text-sm"><p>{t('a2aIngress.outbound.reviewRequired')}</p><PendingDiff agent={agent} label={t('a2aIngress.outbound.endpointChange')} /><div className="mt-3 flex gap-2"><button type="button" className="btn primary" onClick={() => void operate(agent, 'confirm')} disabled={!!busy}>{t('a2aIngress.outbound.confirm')}</button><button type="button" className="btn secondary" onClick={() => void operate(agent, 'reject')} disabled={!!busy}>{t('a2aIngress.outbound.reject')}</button></div></div>}
- </div>)}</div>}
- </section>
- </div>;
+ )}
+ </div>
+ );
+}
+function Value({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) {
+ return (
+ <div className="min-w-0">
+ <div className="text-xs text-text-muted">{label}</div>
+ <div className={`mt-1 break-all text-sm text-text ${mono ? 'font-mono' : ''}`}>{value}</div>
+ </div>
+ );
+}
+function Input({ label, value, onChange, type = 'text' }: { label: string; value: string; onChange: (value: string) => void; type?: 'text' | 'password' }) {
+ return (
+ <label>
+ <span className="text-xs font-medium text-text-muted">{label}</span>
+ <input
+ type={type}
+ className="mt-2 w-full rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
+ value={value}
+ onChange={event => onChange(event.target.value)}
+ />
+ </label>
+ );
+}
+function PendingDiff({ agent, label }: { agent: A2AOutboundAgent; label: string }) {
+ const pending = agent.pending_revision?.selected_interface as Record<string, unknown> | undefined;
+ const nextUrl = typeof pending?.url === 'string' ? pending.url : '';
+ if (!nextUrl || nextUrl === agent.selected_interface.url) return null;
+ return (
+ <div className="mt-2 grid gap-1 rounded-md bg-bg/70 p-2 text-xs">
+ <span className="font-medium text-text">{label}</span>
+ <span className="break-all text-text-muted">{agent.selected_interface.url}</span>
+ <span className="break-all text-warn">→ {nextUrl}</span>
+ </div>
+ );
}
-
-function formatTime(value: string, language: string): string { return new Date(value).toLocaleString(language.startsWith('zh') ? 'zh-CN' : 'en-US', { hour12: false }); }
-function Notice({ tone, children }: { tone: 'warn' | 'danger' | 'ok'; children: React.ReactNode }) { const style = tone === 'danger' ? 'border-danger/30 bg-danger/10' : tone === 'warn' ? 'border-warn/30 bg-warn/10' : 'border-ok/30 bg-ok/10'; return <div className={`rounded-xl border px-4 py-3 text-sm text-text ${style}`}>{children}</div>; }
-function Value({ label, value }: { label: string; value: string }) { return <div><div className="text-text-muted">{label}</div><div className="mt-1 break-all text-text">{value}</div></div>; }
-function Input({ label, value, onChange, type = 'text' }: { label: string; value: string; onChange: (value: string) => void; type?: 'text' | 'password' }) { return <label><span className="text-xs font-medium text-text-muted">{label}</span><input type={type} className="mt-2 w-full rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent" value={value} onChange={event => onChange(event.target.value)} /></label>; }
-function PendingDiff({ agent, label }: { agent: A2AOutboundAgent; label: string }) { const pending = agent.pending_revision?.selected_interface as Record<string, unknown> | undefined; const nextUrl = typeof pending?.url === 'string' ? pending.url : ''; if (!nextUrl || nextUrl === agent.selected_interface.url) return null; return <div className="mt-2 grid gap-1 rounded-md bg-bg/70 p-2 text-xs"><span className="font-medium text-text">{label}</span><span className="break-all text-text-muted">{agent.selected_interface.url}</span><span className="break-all text-warn">→ {nextUrl}</span></div>; }
diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aIngressPanelState.ts b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aIngressPanelState.ts
index a53615478e..be95f6d975 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aIngressPanelState.ts
+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/a2aIngressPanelState.ts
@@ -59,6 +59,40 @@ export interface A2AIngressHistory {
total: number;
}
+export type A2AOutboundDispatchStatus =
+ | 'created'
+ | 'submitting'
+ | 'accepted'
+ | 'working'
+ | 'completed'
+ | 'failed'
+ | 'canceled'
+ | 'rejected'
+ | 'input_required'
+ | 'auth_required'
+ | 'unknown'
+ | 'timed_out'
+ | 'dispatch_failed';
+
+export interface A2AOutboundDispatchRecord {
+ dispatch_id: string;
+ agent_id: string;
+ mode: 'sync' | 'async';
+ status: A2AOutboundDispatchStatus;
+ remote_task_id: string | null;
+ created_at: string;
+ updated_at: string;
+ accepted_at: string | null;
+ finished_at: string | null;
+ error_code: string | null;
+ error_summary: string | null;
+}
+
+export interface A2AOutboundDispatchHistory {
+ items: A2AOutboundDispatchRecord[];
+ total: number;
+}
+
const DEFAULT_DRAFT: A2AIngressDraft = {
host: '127.0.0.1',
port: '19100',
@@ -142,6 +176,53 @@ export function normalizeA2AIngressHistory(value: unknown): A2AIngressHistory |
return { items, total: asNumber(payload.total, items.length) };
}
+export function normalizeA2AOutboundDispatchHistory(value: unknown): A2AOutboundDispatchHistory | null {
+ if (!value || typeof value !== 'object') return null;
+ const payload = value as Record<string, unknown>;
+ if (!Array.isArray(payload.items)) return null;
+ const statuses = new Set<A2AOutboundDispatchStatus>([
+ 'created',
+ 'submitting',
+ 'accepted',
+ 'working',
+ 'completed',
+ 'failed',
+ 'canceled',
+ 'rejected',
+ 'input_required',
+ 'auth_required',
+ 'unknown',
+ 'timed_out',
+ 'dispatch_failed',
+ ]);
+ const items: A2AOutboundDispatchRecord[] = [];
+ for (const rawItem of payload.items) {
+ if (!rawItem || typeof rawItem !== 'object') continue;
+ const item = rawItem as Record<string, unknown>;
+ const dispatchId = asString(item.dispatch_id).trim();
+ const agentId = asString(item.agent_id).trim();
+ const mode = asString(item.mode);
+ const status = asString(item.status) as A2AOutboundDispatchStatus;
+ const createdAt = asString(item.created_at);
+ const updatedAt = asString(item.updated_at, createdAt);
+ if (!dispatchId || !agentId || !['sync', 'async'].includes(mode) || !statuses.has(status) || !createdAt) continue;
+ items.push({
+ dispatch_id: dispatchId,
+ agent_id: agentId,
+ mode: mode as 'sync' | 'async',
+ status,
+ remote_task_id: typeof item.remote_task_id === 'string' ? item.remote_task_id : null,
+ created_at: createdAt,
+ updated_at: updatedAt,
+ accepted_at: typeof item.accepted_at === 'string' ? item.accepted_at : null,
+ finished_at: typeof item.finished_at === 'string' ? item.finished_at : null,
+ error_code: typeof item.error_code === 'string' ? item.error_code : null,
+ error_summary: typeof item.error_summary === 'string' ? item.error_summary : null,
+ });
+ }
+ return { items, total: asNumber(payload.total, items.length) };
+}
+
export function draftFromA2AIngressSnapshot(snapshot: A2AIngressSnapshot): A2AIngressDraft {
return {
host: snapshot.desired_host,
diff --git a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx
index 1e033635c9..7ce3a7bdad 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/A2AIngressPanel/index.tsx
@@ -1,5 +1,6 @@
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 type { WebError } from '../../types/websocket';
import { A2AOutboundPanel } from './A2AOutboundPanel';
import {
@@ -8,12 +9,14 @@ import {
isA2AIngressTransitioning,
normalizeA2AIngressHistory,
normalizeA2AIngressSnapshot,
+ normalizeA2AOutboundDispatchHistory,
shouldAcceptA2AIngressResponse,
toA2AIngressPatch,
validateA2AIngressDraft,
type A2AIngressDraft,
type A2AIngressRequestRecord,
type A2AIngressSnapshot,
+ type A2AOutboundDispatchRecord,
} from './a2aIngressPanelState';
interface A2AIngressPanelProps {
@@ -51,11 +54,19 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)
const [notice, setNotice] = useState<string | null>(null);
const [isDirty, setIsDirty] = useState(false);
const [history, setHistory] = useState<A2AIngressRequestRecord[]>([]);
- const [historyTotal, setHistoryTotal] = useState(0);
const [historyLoading, setHistoryLoading] = useState(false);
const [historyError, setHistoryError] = useState<string | null>(null);
+ const [historyDirection, setHistoryDirection] = useState<'ingress' | 'outbound'>('ingress');
+ const [outboundHistory, setOutboundHistory] = useState<A2AOutboundDispatchRecord[]>([]);
+ const [outboundHistoryLoading, setOutboundHistoryLoading] = useState(false);
+ const [outboundHistoryError, setOutboundHistoryError] = useState<string | null>(null);
+ const [copiedHistoryCell, setCopiedHistoryCell] = useState<string | null>(null);
+ const [copyError, setCopyError] = useState<string | null>(null);
+ const [outboundHeaderActionsContainer, setOutboundHeaderActionsContainer] = useState<HTMLDivElement | null>(null);
const responseGenerationRef = useRef(0);
const historyResponseGenerationRef = useRef(0);
+ const outboundHistoryResponseGenerationRef = useRef(0);
+ const copyFeedbackTimerRef = useRef<number | null>(null);
const acceptSnapshot = useCallback(
(payload: unknown) => {
@@ -69,22 +80,25 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)
[t],
);
- const refresh = useCallback(async (showLoading = true) => {
- if (!isConnected) return;
- const responseGeneration = ++responseGenerationRef.current;
- if (showLoading) setLoading(true);
- try {
- const payload = await request('a2a.ingress.get');
- if (!shouldAcceptA2AIngressResponse(responseGeneration, responseGenerationRef.current)) return;
- acceptSnapshot(payload);
- setError(null);
- } catch (refreshError) {
- if (!shouldAcceptA2AIngressResponse(responseGeneration, responseGenerationRef.current)) return;
- setError(errorMessage(refreshError));
- } finally {
- if (showLoading && shouldAcceptA2AIngressResponse(responseGeneration, responseGenerationRef.current)) setLoading(false);
- }
- }, [acceptSnapshot, isConnected, request]);
+ const refresh = useCallback(
+ async (showLoading = true) => {
+ if (!isConnected) return;
+ const responseGeneration = ++responseGenerationRef.current;
+ if (showLoading) setLoading(true);
+ try {
+ const payload = await request('a2a.ingress.get');
+ if (!shouldAcceptA2AIngressResponse(responseGeneration, responseGenerationRef.current)) return;
+ acceptSnapshot(payload);
+ setError(null);
+ } catch (refreshError) {
+ if (!shouldAcceptA2AIngressResponse(responseGeneration, responseGenerationRef.current)) return;
+ setError(errorMessage(refreshError));
+ } finally {
+ if (showLoading && shouldAcceptA2AIngressResponse(responseGeneration, responseGenerationRef.current)) setLoading(false);
+ }
+ },
+ [acceptSnapshot, isConnected, request],
+ );
useEffect(() => {
void refresh();
@@ -95,32 +109,79 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)
return () => window.clearInterval(timer);
}, [refresh, snapshot?.state]);
- const refreshHistory = useCallback(async (showLoading = true) => {
- if (!isConnected) return;
- const responseGeneration = ++historyResponseGenerationRef.current;
- if (showLoading) setHistoryLoading(true);
- try {
- const payload = await request('a2a.ingress.history', { limit: 200 });
- if (!shouldAcceptA2AIngressResponse(responseGeneration, historyResponseGenerationRef.current)) return;
- const next = normalizeA2AIngressHistory(payload);
- if (!next) throw new Error(t('a2aIngress.errors.invalidHistoryResponse'));
- setHistory(next.items);
- setHistoryTotal(next.total);
- setHistoryError(null);
- } catch (historyRequestError) {
- if (!shouldAcceptA2AIngressResponse(responseGeneration, historyResponseGenerationRef.current)) return;
- setHistoryError(errorMessage(historyRequestError));
- } finally {
- if (showLoading && shouldAcceptA2AIngressResponse(responseGeneration, historyResponseGenerationRef.current)) setHistoryLoading(false);
- }
- }, [isConnected, request, t]);
+ const refreshHistory = useCallback(
+ async (showLoading = true) => {
+ if (!isConnected) return;
+ const responseGeneration = ++historyResponseGenerationRef.current;
+ if (showLoading) setHistoryLoading(true);
+ try {
+ const payload = await request('a2a.ingress.history', { limit: 200 });
+ if (!shouldAcceptA2AIngressResponse(responseGeneration, historyResponseGenerationRef.current)) return;
+ const next = normalizeA2AIngressHistory(payload);
+ if (!next) throw new Error(t('a2aIngress.errors.invalidHistoryResponse'));
+ setHistory(next.items);
+ setHistoryError(null);
+ } catch (historyRequestError) {
+ if (!shouldAcceptA2AIngressResponse(responseGeneration, historyResponseGenerationRef.current)) return;
+ setHistoryError(errorMessage(historyRequestError));
+ } finally {
+ if (showLoading && shouldAcceptA2AIngressResponse(responseGeneration, historyResponseGenerationRef.current)) setHistoryLoading(false);
+ }
+ },
+ [isConnected, request, t],
+ );
+
+ const refreshOutboundHistory = useCallback(
+ async (showLoading = true) => {
+ if (!isConnected) return;
+ const responseGeneration = ++outboundHistoryResponseGenerationRef.current;
+ if (showLoading) setOutboundHistoryLoading(true);
+ try {
+ const payload = await request('a2a.outbound.dispatch.list', { limit: 200 });
+ if (!shouldAcceptA2AIngressResponse(responseGeneration, outboundHistoryResponseGenerationRef.current)) return;
+ const next = normalizeA2AOutboundDispatchHistory(payload);
+ if (!next) throw new Error(t('a2aIngress.errors.invalidHistoryResponse'));
+ setOutboundHistory(next.items);
+ setOutboundHistoryError(null);
+ } catch (historyRequestError) {
+ if (!shouldAcceptA2AIngressResponse(responseGeneration, outboundHistoryResponseGenerationRef.current)) return;
+ setOutboundHistoryError(errorMessage(historyRequestError));
+ } finally {
+ if (showLoading && shouldAcceptA2AIngressResponse(responseGeneration, outboundHistoryResponseGenerationRef.current)) setOutboundHistoryLoading(false);
+ }
+ },
+ [isConnected, request, t],
+ );
useEffect(() => {
if (activeTab !== 'history' || !isConnected) return;
- void refreshHistory();
- const timer = window.setInterval(() => void refreshHistory(false), 2000);
+ const refreshActiveHistory = historyDirection === 'ingress' ? refreshHistory : refreshOutboundHistory;
+ void refreshActiveHistory();
+ const timer = window.setInterval(() => void refreshActiveHistory(false), 2000);
return () => window.clearInterval(timer);
- }, [activeTab, isConnected, refreshHistory]);
+ }, [activeTab, historyDirection, isConnected, refreshHistory, refreshOutboundHistory]);
+
+ useEffect(
+ () => () => {
+ if (copyFeedbackTimerRef.current !== null) window.clearTimeout(copyFeedbackTimerRef.current);
+ },
+ [],
+ );
+
+ const copyHistoryValue = useCallback(
+ async (cellKey: string, value: string) => {
+ try {
+ await navigator.clipboard.writeText(value);
+ setCopyError(null);
+ setCopiedHistoryCell(cellKey);
+ if (copyFeedbackTimerRef.current !== null) window.clearTimeout(copyFeedbackTimerRef.current);
+ copyFeedbackTimerRef.current = window.setTimeout(() => setCopiedHistoryCell(null), 1600);
+ } catch {
+ setCopyError(t('a2aIngress.history.copyFailed'));
+ }
+ },
+ [t],
+ );
const updateDraft = <K extends keyof A2AIngressDraft>(field: K, value: A2AIngressDraft[K]) => {
setDraft(current => (current ? { ...current, [field]: value } : current));
@@ -175,6 +236,11 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)
const canEnable = canOperateA2AIngress(snapshot, isConnected, busy, isDirty, 'enable');
const canDisable = canOperateA2AIngress(snapshot, isConnected, busy, isDirty, 'disable');
const canReload = canOperateA2AIngress(snapshot, isConnected, busy, isDirty, 'reload');
+ const serviceEnabled = snapshot?.enabled === true;
+ const lifecycleOperation = serviceEnabled ? 'disable' : 'enable';
+ const canToggleService = serviceEnabled ? canDisable : canEnable;
+ const activeHistoryLoading = historyDirection === 'ingress' ? historyLoading : outboundHistoryLoading;
+ const refreshActiveHistory = historyDirection === 'ingress' ? refreshHistory : refreshOutboundHistory;
return (
<div className="flex-1 min-h-0">
@@ -184,22 +250,51 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)
<h2 className="text-lg font-semibold">{t('a2aIngress.title')}</h2>
<p className="text-sm text-text-muted mt-1">{t('a2aIngress.subtitle')}</p>
</div>
- {activeTab === 'config' ? <div className="flex flex-wrap gap-2">
- <button type="button" className="btn secondary" onClick={() => void refresh()} disabled={!isConnected || loading || busy}>
- {loading ? t('common.refreshing') : t('common.refresh')}
- </button>
- <button type="button" className="btn primary" onClick={() => void runOperation('enable')} disabled={!canEnable}>
- {operation === 'enable' ? t('a2aIngress.enabling') : t('a2aIngress.enable')}
- </button>
- <button type="button" className="btn secondary" onClick={() => void runOperation('disable')} disabled={!canDisable}>
- {operation === 'disable' ? t('a2aIngress.disabling') : t('a2aIngress.disable')}
- </button>
- <button type="button" className="btn secondary" onClick={() => void runOperation('reload')} disabled={!canReload}>
- {operation === 'reload' ? t('a2aIngress.reloading') : t('a2aIngress.reload')}
+ {activeTab === 'config' ? (
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ className={`btn ${serviceEnabled ? 'secondary text-danger' : 'primary'}`}
+ onClick={() => void runOperation(lifecycleOperation)}
+ disabled={!canToggleService}
+ >
+ <Power className="h-4 w-4" aria-hidden />
+ {operation === 'enable'
+ ? t('a2aIngress.enabling')
+ : operation === 'disable'
+ ? t('a2aIngress.disabling')
+ : t(serviceEnabled ? 'a2aIngress.disable' : 'a2aIngress.enable')}
+ </button>
+ <button
+ type="button"
+ className="btn secondary"
+ onClick={() => void runOperation('reload')}
+ disabled={!canReload}
+ title={t('a2aIngress.restartHint')}
+ >
+ <RotateCw className={`h-4 w-4 ${operation === 'reload' ? 'animate-spin' : ''}`} aria-hidden />
+ {operation === 'reload' ? t('a2aIngress.restarting') : t('a2aIngress.restart')}
+ </button>
+ <div className="ml-1 border-l border-border pl-2">
+ <button
+ type="button"
+ className="btn secondary px-3"
+ onClick={() => void refresh()}
+ disabled={!isConnected || loading || busy}
+ aria-label={t('a2aIngress.refreshStatus')}
+ title={t('a2aIngress.refreshHint')}
+ >
+ <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} aria-hidden />
+ </button>
+ </div>
+ </div>
+ ) : activeTab === 'outbound' ? (
+ <div ref={setOutboundHeaderActionsContainer} className="flex flex-wrap items-center gap-2" />
+ ) : activeTab === 'history' ? (
+ <button type="button" className="btn secondary" onClick={() => void refreshActiveHistory()} disabled={!isConnected || activeHistoryLoading}>
+ {activeHistoryLoading ? t('common.refreshing') : t('common.refresh')}
</button>
- </div> : activeTab === 'history' ? <button type="button" className="btn secondary" onClick={() => void refreshHistory()} disabled={!isConnected || historyLoading}>
- {historyLoading ? t('common.refreshing') : t('common.refresh')}
- </button> : null}
+ ) : null}
</div>
<div className="app-subtabs shrink-0" role="tablist" aria-label={t('a2aIngress.tabs.ariaLabel')}>
{(['config', 'outbound', 'history'] as const).map(tab => (
@@ -218,167 +313,342 @@ export function A2AIngressPanel({ isConnected, request }: A2AIngressPanelProps)
</button>
))}
</div>
- {activeTab === 'config' ? <div id="a2a-ingress-panel-config" role="tabpanel" aria-labelledby="a2a-ingress-tab-config" className="flex min-h-0 flex-1 flex-col gap-5 overflow-auto pr-1 pt-1">
- {!isConnected && <Alert tone="warn">{t('a2aIngress.disconnected')}</Alert>}
- {error && <Alert tone="danger">{error}</Alert>}
- {notice && <Alert tone="ok">{notice}</Alert>}
- {isDirty && <Alert tone="warn">{t('a2aIngress.saveBeforeLifecycleAction')}</Alert>}
- <section className="rounded-xl border border-border bg-panel-strong/60 p-4">
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div>
- <h3 className="text-sm font-semibold text-text">{t('a2aIngress.status.title')}</h3>
- <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.status.configRevision', { revision: snapshot?.config_revision ?? '-' })}</p>
- </div>
- {snapshot && (
- <span className={`rounded-full px-3 py-1 text-sm font-medium ${STATE_BADGE_CLASS[snapshot.state]}`}>
- {t(`a2aIngress.states.${snapshot.state}`)}
- </span>
- )}
- </div>
- <div className="mt-4 grid gap-4 md:grid-cols-2">
- <AddressCard label={t('a2aIngress.status.effectiveRpcUrl')} value={snapshot?.effective_rpc_url} emptyText={t('a2aIngress.status.notListening')} />
- <AddressCard label={t('a2aIngress.status.effectiveCardUrl')} value={snapshot?.effective_card_url} emptyText={t('a2aIngress.status.notListening')} />
- </div>
- {snapshot?.last_error && (
- <Alert tone="danger" className="mt-4">
- {snapshot.last_error}
- </Alert>
- )}
- {snapshot?.exposure_warning && (
- <Alert tone="warn" className="mt-4">
- {snapshot.exposure_warning}
- </Alert>
- )}
- </section>
- {draft && (
- <section className="rounded-xl border border-border bg-panel-strong/60 p-4">
- <div className="flex flex-wrap items-center justify-between gap-4">
- <div>
- <h3 className="text-sm font-semibold text-text">{t('a2aIngress.config.title')}</h3>
- <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.config.description')}</p>
- </div>
- <div className="flex gap-2">
- <button type="button" className="btn secondary" onClick={() => void save(false)} disabled={!isConnected || busy}>
- {operation === 'save' ? t('common.saving') : t('a2aIngress.save')}
- </button>
- <button type="button" className="btn primary" onClick={() => void save(true)} disabled={!isConnected || busy}>
- {operation === 'apply' ? t('a2aIngress.applying') : t('a2aIngress.saveAndApply')}
- </button>
+ {activeTab === 'config' ? (
+ <div
+ id="a2a-ingress-panel-config"
+ role="tabpanel"
+ aria-labelledby="a2a-ingress-tab-config"
+ className="flex min-h-0 flex-1 flex-col gap-5 overflow-auto pr-1 pt-1"
+ >
+ {!isConnected && <Alert tone="warn">{t('a2aIngress.disconnected')}</Alert>}
+ {error && <Alert tone="danger">{error}</Alert>}
+ {notice && <Alert tone="ok">{notice}</Alert>}
+ {isDirty && <Alert tone="warn">{t('a2aIngress.saveBeforeLifecycleAction')}</Alert>}
+ <section className="rounded-xl border border-border bg-panel-strong/60 p-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div>
+ <h3 className="text-sm font-semibold text-text">{t('a2aIngress.status.title')}</h3>
+ <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.status.configRevision', { revision: snapshot?.config_revision ?? '-' })}</p>
+ </div>
+ {snapshot && (
+ <span className={`rounded-full px-3 py-1 text-sm font-medium ${STATE_BADGE_CLASS[snapshot.state]}`}>
+ {t(`a2aIngress.states.${snapshot.state}`)}
+ </span>
+ )}
</div>
- </div>
- <div className="mt-4 grid gap-4 md:grid-cols-2">
- <TextField label={t('a2aIngress.fields.host')} value={draft.host} onChange={value => updateDraft('host', value)} disabled={busy} />
- <TextField
- label={t('a2aIngress.fields.port')}
- value={draft.port}
- onChange={value => updateDraft('port', value)}
- disabled={busy}
- type="number"
- min={1}
- max={65535}
- />
- <TextField label={t('a2aIngress.fields.rpc_path')} value={draft.rpc_path} onChange={value => updateDraft('rpc_path', value)} disabled={busy} />
- <TextField label={t('a2aIngress.fields.card_path')} value={draft.card_path} onChange={value => updateDraft('card_path', value)} disabled={busy} />
- <TextField
- label={t('a2aIngress.fields.extended_card_path')}
- value={draft.extended_card_path}
- onChange={value => updateDraft('extended_card_path', value)}
- disabled={busy}
- />
- <TextField
- label={t('a2aIngress.fields.protocol_version')}
- value={draft.protocol_version}
- onChange={value => updateDraft('protocol_version', value)}
- disabled={busy}
- />
- <TextField label={t('a2aIngress.fields.app_name')} value={draft.app_name} onChange={value => updateDraft('app_name', value)} disabled={busy} />
- <TextField
- label={t('a2aIngress.fields.app_version')}
- value={draft.app_version}
- onChange={value => updateDraft('app_version', value)}
- disabled={busy}
- />
- <label className="md:col-span-2">
- <span className="text-xs font-medium text-text-muted">{t('a2aIngress.fields.app_description')}</span>
- <textarea
- className="mt-2 min-h-20 w-full resize-y rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
- value={draft.app_description}
- onChange={event => updateDraft('app_description', event.target.value)}
- disabled={busy}
+ <div className="mt-4 grid gap-4 md:grid-cols-2">
+ <AddressCard
+ label={t('a2aIngress.status.effectiveRpcUrl')}
+ value={snapshot?.effective_rpc_url}
+ emptyText={t('a2aIngress.status.notListening')}
/>
- </label>
- <label className="flex items-center gap-3 rounded-lg border border-border bg-bg px-3 py-3 md:col-span-2">
- <input
- type="checkbox"
- checked={draft.expose_reasoning}
- onChange={event => updateDraft('expose_reasoning', event.target.checked)}
- disabled={busy}
- className="h-4 w-4 accent-[var(--color-accent)]"
+ <AddressCard
+ label={t('a2aIngress.status.effectiveCardUrl')}
+ value={snapshot?.effective_card_url}
+ emptyText={t('a2aIngress.status.notListening')}
/>
- <span className="text-sm text-text">{t('a2aIngress.fields.expose_reasoning')}</span>
- </label>
- </div>
- </section>
- )}
- </div> : activeTab === 'outbound' ? <div id="a2a-ingress-panel-outbound" role="tabpanel" aria-labelledby="a2a-ingress-tab-outbound" className="flex min-h-0 flex-1 flex-col pt-1"><A2AOutboundPanel isConnected={isConnected} request={request} /></div> : <div id="a2a-ingress-panel-history" role="tabpanel" aria-labelledby="a2a-ingress-tab-history" className="flex min-h-0 flex-1 flex-col gap-3 pt-1">
- {!isConnected && <Alert tone="warn">{t('a2aIngress.disconnected')}</Alert>}
- {historyError && <Alert tone="danger">{historyError}</Alert>}
- <section className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-panel-strong/60">
- <div className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3">
- <div>
- <h3 className="text-sm font-semibold text-text">{t('a2aIngress.history.title')}</h3>
- <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.history.description')}</p>
</div>
- <span className="text-xs text-text-muted">{t('a2aIngress.history.total', { count: historyTotal })}</span>
- </div>
- {historyLoading && history.length === 0 ? (
- <div className="grid min-h-0 flex-1 place-items-center px-4 py-12 text-center text-sm text-text-muted">{t('common.loading')}</div>
- ) : history.length === 0 ? (
- <div className="grid min-h-0 flex-1 place-items-center px-4 py-12 text-center">
- <div>
- <div className="text-sm font-medium text-text">{t('a2aIngress.history.empty')}</div>
- <div className="mt-1 text-xs text-text-muted">{t('a2aIngress.history.emptyDescription')}</div>
+ {snapshot?.last_error && (
+ <Alert tone="danger" className="mt-4">
+ {snapshot.last_error}
+ </Alert>
+ )}
+ {snapshot?.exposure_warning && (
+ <Alert tone="warn" className="mt-4">
+ {snapshot.exposure_warning}
+ </Alert>
+ )}
+ </section>
+ {draft && (
+ <section className="rounded-xl border border-border bg-panel-strong/60 p-4">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <div>
+ <h3 className="text-sm font-semibold text-text">{t('a2aIngress.config.title')}</h3>
+ <p className="mt-1 text-xs text-text-muted">{t('a2aIngress.config.description')}</p>
+ </div>
+ <div className="flex gap-2">
+ <button type="button" className="btn secondary" onClick={() => void save(false)} disabled={!isConnected || busy}>
+ {operation === 'save' ? t('common.saving') : t('a2aIngress.save')}
+ </button>
+ <button type="button" className="btn primary" onClick={() => void save(true)} disabled={!isConnected || busy}>
+ {operation === 'apply' ? t('a2aIngress.applying') : t('a2aIngress.saveAndApply')}
+ </button>
+ </div>
</div>
- </div>
- ) : (
- <div className="min-h-0 flex-1 overflow-auto">
- <table className="w-full min-w-[920px] text-left text-sm">
- <thead className="sticky top-0 z-10 bg-bg text-xs text-text-muted">
- <tr>
- <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.status')}</th>
- <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.operation')}</th>
- <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.requestId')}</th>
- <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.contextId')}</th>
- <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.startedAt')}</th>
- <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.duration')}</th>
- <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.error')}</th>
- </tr>
- </thead>
- <tbody className="divide-y divide-border">
- {history.map(item => (
- <tr key={item.request_id} className="text-text">
- <td className="px-4 py-3"><span className={`rounded-full px-2.5 py-1 text-xs font-medium ${REQUEST_BADGE_CLASS[item.status]}`}>{t(`a2aIngress.history.statuses.${item.status}`)}</span></td>
- <td className="px-4 py-3">{t(`a2aIngress.history.operations.${item.operation}`, { defaultValue: item.operation })}</td>
- <td className="max-w-48 truncate px-4 py-3 font-mono text-xs" title={item.request_id}>{item.request_id}</td>
- <td className="max-w-48 truncate px-4 py-3 font-mono text-xs" title={item.context_id || undefined}>{item.context_id || '-'}</td>
- <td className="whitespace-nowrap px-4 py-3">{formatTimestamp(item.started_at, i18n.language)}</td>
- <td className="whitespace-nowrap px-4 py-3">{formatDuration(item.duration_ms, t('a2aIngress.history.processing'))}</td>
- <td className="max-w-64 px-4 py-3 text-xs text-danger"><span className="line-clamp-2" title={item.error || undefined}>{item.error || '-'}</span></td>
- </tr>
+ <div className="mt-4 grid gap-4 md:grid-cols-2">
+ <TextField label={t('a2aIngress.fields.host')} value={draft.host} onChange={value => updateDraft('host', value)} disabled={busy} />
+ <TextField
+ label={t('a2aIngress.fields.port')}
+ value={draft.port}
+ onChange={value => updateDraft('port', value)}
+ disabled={busy}
+ type="number"
+ min={1}
+ max={65535}
+ />
+ <TextField
+ label={t('a2aIngress.fields.rpc_path')}
+ value={draft.rpc_path}
+ onChange={value => updateDraft('rpc_path', value)}
+ disabled={busy}
+ />
+ <TextField
+ label={t('a2aIngress.fields.card_path')}
+ value={draft.card_path}
+ onChange={value => updateDraft('card_path', value)}
+ disabled={busy}
+ />
+ <TextField
+ label={t('a2aIngress.fields.extended_card_path')}
+ value={draft.extended_card_path}
+ onChange={value => updateDraft('extended_card_path', value)}
+ disabled={busy}
+ />
+ <TextField
+ label={t('a2aIngress.fields.protocol_version')}
+ value={draft.protocol_version}
+ onChange={value => updateDraft('protocol_version', value)}
+ disabled={busy}
+ />
+ <TextField
+ label={t('a2aIngress.fields.app_name')}
+ value={draft.app_name}
+ onChange={value => updateDraft('app_name', value)}
+ disabled={busy}
+ />
+ <TextField
+ label={t('a2aIngress.fields.app_version')}
+ value={draft.app_version}
+ onChange={value => updateDraft('app_version', value)}
+ disabled={busy}
+ />
+ <label className="md:col-span-2">
+ <span className="text-xs font-medium text-text-muted">{t('a2aIngress.fields.app_description')}</span>
+ <textarea
+ className="mt-2 min-h-20 w-full resize-y rounded-md border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
+ value={draft.app_description}
+ onChange={event => updateDraft('app_description', event.target.value)}
+ disabled={busy}
+ />
+ </label>
+ <label className="flex items-center gap-3 rounded-lg border border-border bg-bg px-3 py-3 md:col-span-2">
+ <input
+ type="checkbox"
+ checked={draft.expose_reasoning}
+ onChange={event => updateDraft('expose_reasoning', event.target.checked)}
+ disabled={busy}
+ className="h-4 w-4 accent-[var(--color-accent)]"
+ />
+ <span className="text-sm text-text">{t('a2aIngress.fields.expose_reasoning')}</span>
+ </label>
+ </div>
+ </section>
+ )}
+ </div>
+ ) : activeTab === 'outbound' ? (
+ <div id="a2a-ingress-panel-outbound" role="tabpanel" aria-labelledby="a2a-ingress-tab-outbound" className="flex min-h-0 flex-1 flex-col pt-1">
+ <A2AOutboundPanel isConnected={isConnected} request={request} headerActionsContainer={outboundHeaderActionsContainer} />
+ </div>
+ ) : (
+ <div id="a2a-ingress-panel-history" role="tabpanel" aria-labelledby="a2a-ingress-tab-history" className="flex min-h-0 flex-1 flex-col gap-3 pt-1">
+ {!isConnected && <Alert tone="warn">{t('a2aIngress.disconnected')}</Alert>}
+ {copyError && (
+ <Alert tone="danger" onClose={() => setCopyError(null)} closeLabel={t('common.close')}>
+ {copyError}
+ </Alert>
+ )}
+ {(historyDirection === 'ingress' ? historyError : outboundHistoryError) && (
+ <Alert tone="danger">{historyDirection === 'ingress' ? historyError : outboundHistoryError}</Alert>
+ )}
+ <section className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-panel-strong/60">
+ <div className="shrink-0 border-b border-border px-4 py-3">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <div className="min-w-0">
+ <h3 className="text-sm font-semibold text-text">{t(`a2aIngress.history.${historyDirection}.title`)}</h3>
+ <p className="mt-1 text-xs text-text-muted">{t(`a2aIngress.history.${historyDirection}.description`)}</p>
+ </div>
+ <div
+ className="ml-auto inline-flex shrink-0 rounded-lg border border-border bg-secondary/50 p-1"
+ role="tablist"
+ aria-label={t('a2aIngress.history.tabs.ariaLabel')}
+ >
+ {(['ingress', 'outbound'] as const).map(direction => (
+ <button
+ key={direction}
+ type="button"
+ role="tab"
+ aria-selected={historyDirection === direction}
+ className={`rounded-md px-4 py-1.5 text-sm font-medium transition-colors ${historyDirection === direction ? 'bg-bg text-accent shadow-sm' : 'text-text-muted hover:bg-bg/60 hover:text-text'}`}
+ onClick={() => setHistoryDirection(direction)}
+ >
+ {t(`a2aIngress.history.tabs.${direction}`)}
+ </button>
))}
- </tbody>
- </table>
+ </div>
+ </div>
</div>
- )}
- </section>
- </div>}
+ {historyDirection === 'ingress' ? (
+ historyLoading && history.length === 0 ? (
+ <div className="grid min-h-0 flex-1 place-items-center px-4 py-12 text-center text-sm text-text-muted">{t('common.loading')}</div>
+ ) : history.length === 0 ? (
+ <div className="grid min-h-0 flex-1 place-items-center px-4 py-12 text-center">
+ <div>
+ <div className="text-sm font-medium text-text">{t('a2aIngress.history.ingress.empty')}</div>
+ <div className="mt-1 text-xs text-text-muted">{t('a2aIngress.history.ingress.emptyDescription')}</div>
+ </div>
+ </div>
+ ) : (
+ <div className="min-h-0 flex-1 overflow-auto">
+ <table className="w-full min-w-[920px] text-left text-sm">
+ <thead className="sticky top-0 z-10 border-b border-border bg-secondary/60 text-xs text-text-muted">
+ <tr>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.status')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.operation')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.requestId')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.contextId')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.startedAt')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.duration')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.error')}</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-border">
+ {history.map(item => (
+ <tr key={item.request_id} className="text-text">
+ <td className="px-4 py-3">
+ <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${REQUEST_BADGE_CLASS[item.status]}`}>
+ {t(`a2aIngress.history.statuses.${item.status}`)}
+ </span>
+ </td>
+ <td className="px-4 py-3">{t(`a2aIngress.history.operations.${item.operation}`, { defaultValue: item.operation })}</td>
+ <td className="max-w-48 px-4 py-3 font-mono text-xs">
+ <CopyableHistoryValue
+ value={item.request_id}
+ copied={copiedHistoryCell === `ingress:${item.request_id}:request`}
+ onCopy={() => void copyHistoryValue(`ingress:${item.request_id}:request`, item.request_id)}
+ copyLabel={t('a2aIngress.history.copy')}
+ copiedLabel={t('a2aIngress.history.copied')}
+ />
+ </td>
+ <td className="max-w-48 px-4 py-3 font-mono text-xs">
+ <CopyableHistoryValue
+ value={item.context_id}
+ copied={copiedHistoryCell === `ingress:${item.request_id}:context`}
+ onCopy={() => item.context_id && void copyHistoryValue(`ingress:${item.request_id}:context`, item.context_id)}
+ copyLabel={t('a2aIngress.history.copy')}
+ copiedLabel={t('a2aIngress.history.copied')}
+ />
+ </td>
+ <td className="whitespace-nowrap px-4 py-3">{formatTimestamp(item.started_at, i18n.language)}</td>
+ <td className="whitespace-nowrap px-4 py-3">{formatDuration(item.duration_ms, t('a2aIngress.history.processing'))}</td>
+ <td className="max-w-64 px-4 py-3 text-xs text-danger">
+ <CopyableHistoryValue
+ value={item.error}
+ copied={copiedHistoryCell === `ingress:${item.request_id}:error`}
+ onCopy={() => item.error && void copyHistoryValue(`ingress:${item.request_id}:error`, item.error)}
+ copyLabel={t('a2aIngress.history.copy')}
+ copiedLabel={t('a2aIngress.history.copied')}
+ multiline
+ />
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )
+ ) : outboundHistoryLoading && outboundHistory.length === 0 ? (
+ <div className="grid min-h-0 flex-1 place-items-center px-4 py-12 text-center text-sm text-text-muted">{t('common.loading')}</div>
+ ) : outboundHistory.length === 0 ? (
+ <div className="grid min-h-0 flex-1 place-items-center px-4 py-12 text-center">
+ <div>
+ <div className="text-sm font-medium text-text">{t('a2aIngress.history.outbound.empty')}</div>
+ <div className="mt-1 text-xs text-text-muted">{t('a2aIngress.history.outbound.emptyDescription')}</div>
+ </div>
+ </div>
+ ) : (
+ <div className="min-h-0 flex-1 overflow-auto">
+ <table className="w-full min-w-[1080px] text-left text-sm">
+ <thead className="sticky top-0 z-10 border-b border-border bg-secondary/60 text-xs text-text-muted">
+ <tr>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.status')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.mode')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.agentId')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.dispatchId')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.remoteTaskId')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.startedAt')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.duration')}</th>
+ <th className="px-4 py-3 font-medium">{t('a2aIngress.history.columns.error')}</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-border">
+ {outboundHistory.map(item => (
+ <tr key={item.dispatch_id} className="text-text">
+ <td className="px-4 py-3">
+ <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${outboundStatusBadgeClass(item.status)}`}>
+ {t(`a2aIngress.history.outbound.statuses.${item.status}`)}
+ </span>
+ </td>
+ <td className="px-4 py-3">{t(`a2aIngress.history.outbound.modes.${item.mode}`)}</td>
+ <td className="max-w-48 px-4 py-3 font-mono text-xs">
+ <CopyableHistoryValue
+ value={item.agent_id}
+ copied={copiedHistoryCell === `outbound:${item.dispatch_id}:agent`}
+ onCopy={() => void copyHistoryValue(`outbound:${item.dispatch_id}:agent`, item.agent_id)}
+ copyLabel={t('a2aIngress.history.copy')}
+ copiedLabel={t('a2aIngress.history.copied')}
+ />
+ </td>
+ <td className="max-w-48 px-4 py-3 font-mono text-xs">
+ <CopyableHistoryValue
+ value={item.dispatch_id}
+ copied={copiedHistoryCell === `outbound:${item.dispatch_id}:dispatch`}
+ onCopy={() => void copyHistoryValue(`outbound:${item.dispatch_id}:dispatch`, item.dispatch_id)}
+ copyLabel={t('a2aIngress.history.copy')}
+ copiedLabel={t('a2aIngress.history.copied')}
+ />
+ </td>
+ <td className="max-w-48 px-4 py-3 font-mono text-xs">
+ <CopyableHistoryValue
+ value={item.remote_task_id}
+ copied={copiedHistoryCell === `outbound:${item.dispatch_id}:remote`}
+ onCopy={() => item.remote_task_id && void copyHistoryValue(`outbound:${item.dispatch_id}:remote`, item.remote_task_id)}
+ copyLabel={t('a2aIngress.history.copy')}
+ copiedLabel={t('a2aIngress.history.copied')}
+ />
+ </td>
+ <td className="whitespace-nowrap px-4 py-3">{formatTimestamp(item.created_at, i18n.language)}</td>
+ <td className="whitespace-nowrap px-4 py-3">{formatOutboundDuration(item, t('a2aIngress.history.processing'))}</td>
+ <td className="max-w-64 px-4 py-3 text-xs text-danger">
+ <CopyableHistoryValue
+ value={item.error_summary || item.error_code}
+ copied={copiedHistoryCell === `outbound:${item.dispatch_id}:error`}
+ onCopy={() => {
+ const value = item.error_summary || item.error_code;
+ if (value) void copyHistoryValue(`outbound:${item.dispatch_id}:error`, value);
+ }}
+ copyLabel={t('a2aIngress.history.copy')}
+ copiedLabel={t('a2aIngress.history.copied')}
+ multiline
+ />
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </section>
+ </div>
+ )}
</div>
</div>
);
}
-function formatTimestamp(timestamp: number, language: string): string {
- return new Date(timestamp * 1000).toLocaleString(language.startsWith('zh') ? 'zh-CN' : 'en-US', { hour12: false });
+function formatTimestamp(timestamp: number | string, language: string): string {
+ const date = typeof timestamp === 'number' ? new Date(timestamp * 1000) : new Date(timestamp);
+ if (Number.isNaN(date.getTime())) return '-';
+ return date.toLocaleString(language.startsWith('zh') ? 'zh-CN' : 'en-US', { hour12: false });
}
function formatDuration(durationMs: number | null, processingText: string): string {
@@ -387,9 +657,80 @@ function formatDuration(durationMs: number | null, processingText: string): stri
return `${(durationMs / 1000).toFixed(2)} s`;
}
-function Alert({ tone, className = '', children }: { tone: 'warn' | 'danger' | 'ok'; className?: string; children: ReactNode }) {
+function formatOutboundDuration(item: A2AOutboundDispatchRecord, processingText: string): string {
+ if (['created', 'submitting', 'accepted', 'working'].includes(item.status)) return processingText;
+ const observedEnd = item.finished_at || item.updated_at;
+ if (!observedEnd) return '-';
+ const durationMs = Date.parse(observedEnd) - Date.parse(item.created_at);
+ return Number.isFinite(durationMs) && durationMs >= 0 ? formatDuration(durationMs, processingText) : '-';
+}
+
+function outboundStatusBadgeClass(status: A2AOutboundDispatchRecord['status']): string {
+ if (status === 'completed') return 'bg-ok/15 text-ok';
+ if (['failed', 'rejected', 'auth_required', 'dispatch_failed'].includes(status)) return 'bg-danger/15 text-danger';
+ if (status === 'canceled') return 'bg-secondary text-text-muted';
+ if (['input_required', 'unknown', 'timed_out'].includes(status)) return 'bg-warn/15 text-warn';
+ return 'bg-accent/15 text-accent';
+}
+
+function CopyableHistoryValue({
+ value,
+ copied,
+ onCopy,
+ copyLabel,
+ copiedLabel,
+ multiline = false,
+}: {
+ value: string | null;
+ copied: boolean;
+ onCopy: () => void;
+ copyLabel: string;
+ copiedLabel: string;
+ multiline?: boolean;
+}) {
+ if (!value) return <span className="text-text-muted">-</span>;
+ return (
+ <button
+ type="button"
+ className="group flex w-full max-w-full items-start gap-1.5 text-left outline-none transition-colors hover:text-accent focus-visible:text-accent"
+ onClick={onCopy}
+ title={copied ? copiedLabel : value}
+ aria-label={`${copied ? copiedLabel : copyLabel}: ${value}`}
+ >
+ <span className={multiline ? 'line-clamp-2 min-w-0' : 'min-w-0 truncate'}>{value}</span>
+ {copied ? (
+ <Check size={13} className="mt-0.5 shrink-0 text-ok" aria-hidden="true" />
+ ) : (
+ <Copy size={13} className="mt-0.5 shrink-0 text-text-muted group-hover:text-accent" aria-hidden="true" />
+ )}
+ </button>
+ );
+}
+
+function Alert({
+ tone,
+ className = '',
+ children,
+ onClose,
+ closeLabel,
+}: {
+ tone: 'warn' | 'danger' | 'ok';
+ className?: string;
+ children: ReactNode;
+ onClose?: () => void;
+ closeLabel?: string;
+}) {
const toneClass = tone === 'danger' ? 'border-danger/30 bg-danger/10' : tone === 'warn' ? 'border-warn/30 bg-warn/10' : 'border-ok/30 bg-ok/10';
- return <div className={`rounded-xl border px-4 py-3 text-sm text-text ${toneClass} ${className}`}>{children}</div>;
+ return (
+ <div className={`flex items-center gap-3 rounded-xl border px-4 py-3 text-sm text-text ${toneClass} ${className}`}>
+ <div className="min-w-0 flex-1">{children}</div>
+ {onClose && (
+ <button type="button" className="shrink-0 rounded-md p-1 text-text-muted hover:bg-bg/60 hover:text-text" onClick={onClose} aria-label={closeLabel}>
+ <X size={16} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ );
}
function AddressCard({ label, value, emptyText }: { label: string; value: string | null | undefined; emptyText: string }) {
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index cfba7c61cd..b6a0a1eb96 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -317,7 +317,7 @@
"placeholder": "Select Model"
},
"configLockedHistory": "Session has messages — create a new session to change config",
- "modeSwitchDisabledProcessing":"This conversation is running. Start a new conversation to choose another mode",
+ "modeSwitchDisabledProcessing": "This conversation is running. Start a new conversation to choose another mode",
"modeSwitchTitle": "Switch Mode",
"modeSwitchConfirm": "Current session has history messages. Switching mode will create a new session. Continue?",
"skills": "Skills",
@@ -558,34 +558,170 @@
"a2aIngress": {
"title": "A2A Control Center",
"subtitle": "Manage the A2A service exposed by JiuwenSwarm.",
- "tabs": { "ariaLabel": "A2A Control Center pages", "config": "Ingress Configuration", "outbound": "Outbound Configuration", "history": "Processing History" },
- "enable": "Enable service", "enabling": "Enabling...", "disable": "Disable service", "disabling": "Disabling...", "reload": "Reload", "reloading": "Reloading...",
- "save": "Save configuration", "saveAndApply": "Save and apply", "applying": "Applying...", "saved": "Configuration saved; it has not been applied to the running service.", "savedAndApplied": "Configuration saved and applied.",
+ "tabs": {
+ "ariaLabel": "A2A Control Center pages",
+ "config": "Ingress Configuration",
+ "outbound": "Outbound Configuration",
+ "history": "Processing History"
+ },
+ "enable": "Enable service",
+ "enabling": "Enabling...",
+ "disable": "Disable service",
+ "disabling": "Disabling...",
+ "restart": "Restart service",
+ "restarting": "Restarting...",
+ "restartHint": "Stop and restart the ingress service. Existing connections may be briefly interrupted.",
+ "refreshStatus": "Refresh status",
+ "refreshHint": "Fetch the latest status and configuration without restarting the service.",
+ "save": "Save configuration",
+ "saveAndApply": "Save and apply",
+ "applying": "Applying...",
+ "saved": "Configuration saved; it has not been applied to the running service.",
+ "savedAndApplied": "Configuration saved and applied.",
"disconnected": "Gateway is disconnected, so the A2A service cannot be read or changed.",
- "saveBeforeLifecycleAction": "Configuration has unsaved changes. Save it before enabling, disabling, or reloading the service.",
+ "saveBeforeLifecycleAction": "Configuration has unsaved changes. Save it before enabling, disabling, or restarting the service.",
"states": { "disabled": "Disabled", "starting": "Starting", "running": "Running", "stopping": "Stopping", "error": "Error" },
- "status": { "title": "Service status", "configRevision": "Configuration revision: {{revision}}", "effectiveRpcUrl": "Effective JSON-RPC URL", "effectiveCardUrl": "Effective Agent Card URL", "notListening": "Not listening" },
+ "status": {
+ "title": "Service status",
+ "configRevision": "Configuration revision: {{revision}}",
+ "effectiveRpcUrl": "Effective JSON-RPC URL",
+ "effectiveCardUrl": "Effective Agent Card URL",
+ "notListening": "Not listening"
+ },
"config": { "title": "Ingress configuration", "description": "Save updates the desired configuration only; Save and apply reloads the running service." },
"outbound": {
- "localDebug": { "title": "Local Agent debugging", "description": "Controls whether plaintext HTTP Agents on loopback addresses may be discovered and called. Changes apply immediately after saving.", "allow": "Allow local HTTP Agents", "warning": "For local E2E debugging only. This relaxes SSRF protection for 127.0.0.1 / ::1 and must remain disabled in production.", "saving": "Saving...", "saved": "Outbound local debugging settings were saved and applied immediately." },
- "discovery": { "title": "Discover a third-party Agent", "description": "Discovery only fetches and previews the Agent Card. JiuwenSwarm can call the Agent only after explicit registration.", "action": "Discover Agent", "discovering": "Discovering...", "previewOnly": "Preview only, not registered", "previewReady": "Discovery succeeded. Review and explicitly register this candidate before it can be called.", "advanced": "Advanced settings" },
- "list": { "title": "Registered Agents", "total": "{{count}} total", "empty": "No third-party Agents are registered" },
- "fields": { "version": "Version", "endpoint": "Effective endpoint", "protocol": "Protocol", "expiresAt": "Candidate expires", "displayName": "Display name", "credential": "API Key / Bearer (optional, never displayed)", "revision": "Card revision", "credentialState": "Credential", "lastChecked": "Last checked", "connectTimeout": "Connect timeout (seconds)", "syncWait": "Sync wait timeout (seconds)", "replaceCredential": "Replace credential (leave blank to keep)" },
+ "localDebug": {
+ "title": "Local Agent debugging",
+ "description": "Controls whether plaintext HTTP Agents on loopback addresses may be discovered and called. Changes apply immediately after saving.",
+ "allow": "Allow local HTTP Agents",
+ "warning": "For local E2E debugging only. This relaxes SSRF protection for 127.0.0.1 / ::1 and must remain disabled in production.",
+ "saving": "Saving...",
+ "saved": "Outbound local debugging settings were saved and applied immediately."
+ },
+ "discovery": {
+ "title": "Discover a third-party Agent",
+ "description": "Discovery only fetches and previews the Agent Card. JiuwenSwarm can call the Agent only after explicit registration.",
+ "urlLabel": "Agent Card URL",
+ "action": "Discover Agent",
+ "discovering": "Discovering...",
+ "previewOnly": "Preview only, not registered",
+ "previewReady": "Discovery succeeded. Review and explicitly register this candidate before it can be called.",
+ "candidateTitle": "Agent awaiting registration",
+ "candidateDescription": "Review the discovery result and complete the registration details before adding it to the callable list.",
+ "registrationTitle": "Registration details",
+ "registrationDescription": "Set the display name in JiuwenSwarm and provide call credentials when required.",
+ "advanced": "Advanced settings"
+ },
+ "list": {
+ "title": "Registered Agents",
+ "description": "Manage availability, connection settings, and Agent Card updates.",
+ "empty": "No third-party Agents are registered"
+ },
+ "fields": {
+ "version": "Version",
+ "endpoint": "Effective endpoint",
+ "protocol": "Protocol",
+ "expiresAt": "Candidate expires",
+ "displayName": "Display name",
+ "credential": "API Key / Bearer (optional, never displayed)",
+ "revision": "Card revision",
+ "credentialState": "Credential",
+ "lastChecked": "Last checked",
+ "connectTimeout": "Connect timeout (seconds)",
+ "syncWait": "Sync wait timeout (seconds)",
+ "replaceCredential": "Replace credential (leave blank to keep)"
+ },
"availability": { "available": "Available", "unreachable": "Unreachable", "incompatible": "Incompatible", "review_required": "Review required" },
- "register": "Register", "registering": "Registering...", "registered": "The third-party Agent is registered and can now participate in outbound calls when enabled and available.",
- "enabled": "Enabled", "disabled": "Disabled", "enable": "Enable", "disable": "Disable", "refresh": "Refresh Card",
- "configured": "Configured", "notConfigured": "Not configured", "settings": "Settings", "saved": "Registration settings saved.", "clearCredential": "Clear saved credential", "reviewRequired": "A critical endpoint, protocol, security, or identity change was detected. New calls are paused until confirmation.", "endpointChange": "Endpoint change",
- "confirm": "Confirm and apply", "reject": "Reject change", "deleteConfirm": "Delete this registration? Existing dispatch history is retained, but new calls will be rejected immediately.",
- "errors": { "invalidResponse": "The A2A outbound manager returned invalid data.", "invalidSettings": "Enter a valid display name and timeout values greater than zero." }
+ "register": "Register",
+ "registering": "Registering...",
+ "registered": "The third-party Agent is registered and can now participate in outbound calls when enabled and available.",
+ "enabled": "Enabled",
+ "disabled": "Disabled",
+ "enable": "Enable",
+ "disable": "Disable",
+ "refresh": "Refresh Card",
+ "configured": "Configured",
+ "notConfigured": "Not configured",
+ "settings": "Settings",
+ "saved": "Registration settings saved.",
+ "clearCredential": "Clear saved credential",
+ "reviewRequired": "A critical endpoint, protocol, security, or identity change was detected. New calls are paused until confirmation.",
+ "endpointChange": "Endpoint change",
+ "confirm": "Confirm and apply",
+ "reject": "Reject change",
+ "deleteConfirm": "Delete this registration? Existing dispatch history is retained, but new calls will be rejected immediately.",
+ "errors": {
+ "invalidResponse": "The A2A outbound manager returned invalid data.",
+ "invalidSettings": "Enter a valid display name and timeout values greater than zero."
+ }
},
"history": {
- "title": "Ingress request history", "description": "Shows the latest 200 A2A ingress requests in this Gateway process without retaining request bodies.", "total": "{{count}} total", "empty": "No processing history", "emptyDescription": "Incoming A2A request statuses will appear here.", "processing": "Processing",
+ "tabs": { "ariaLabel": "A2A request history direction", "ingress": "Ingress", "outbound": "Outbound" },
+ "copy": "Click to copy",
+ "copied": "Copied",
+ "copyFailed": "Copy failed. Check the browser clipboard permission.",
+ "ingress": {
+ "title": "Ingress request history",
+ "description": "Shows the latest 200 A2A ingress requests in this Gateway process without retaining request bodies.",
+ "empty": "No ingress history",
+ "emptyDescription": "Incoming A2A request statuses will appear here."
+ },
+ "outbound": {
+ "title": "Outbound request history",
+ "description": "Shows the latest 200 A2A outbound dispatches without request or response bodies.",
+ "empty": "No outbound history",
+ "emptyDescription": "Dispatch statuses will appear after requests are sent to third-party Agents.",
+ "modes": { "sync": "Sync", "async": "Async" },
+ "statuses": {
+ "created": "Created",
+ "submitting": "Submitting",
+ "accepted": "Accepted",
+ "working": "Working",
+ "completed": "Completed",
+ "failed": "Failed",
+ "canceled": "Canceled",
+ "rejected": "Rejected",
+ "input_required": "Input required",
+ "auth_required": "Authentication required",
+ "unknown": "Unknown",
+ "timed_out": "Timed out",
+ "dispatch_failed": "Dispatch failed"
+ }
+ },
+ "processing": "Processing",
"statuses": { "processing": "Processing", "completed": "Completed", "failed": "Failed", "canceled": "Canceled" },
"operations": { "message": "Message" },
- "columns": { "status": "Status", "operation": "Request type", "requestId": "Request ID", "contextId": "Context ID", "startedAt": "Started", "duration": "Duration", "error": "Error" }
+ "columns": {
+ "status": "Status",
+ "operation": "Request type",
+ "requestId": "Request ID",
+ "contextId": "Context ID",
+ "mode": "Mode",
+ "agentId": "Agent ID",
+ "dispatchId": "Dispatch ID",
+ "remoteTaskId": "Remote task ID",
+ "startedAt": "Started",
+ "duration": "Duration",
+ "error": "Error"
+ }
+ },
+ "fields": {
+ "host": "Bind host",
+ "port": "Bind port",
+ "rpc_path": "RPC path",
+ "card_path": "Agent Card path",
+ "extended_card_path": "Extended Card path",
+ "protocol_version": "Protocol version",
+ "app_name": "Agent name",
+ "app_description": "Agent description",
+ "app_version": "Agent version",
+ "expose_reasoning": "Expose reasoning in A2A responses"
},
- "fields": { "host": "Bind host", "port": "Bind port", "rpc_path": "RPC path", "card_path": "Agent Card path", "extended_card_path": "Extended Card path", "protocol_version": "Protocol version", "app_name": "Agent name", "app_description": "Agent description", "app_version": "Agent version", "expose_reasoning": "Expose reasoning in A2A responses" },
- "errors": { "invalidResponse": "The A2A service returned an invalid status.", "invalidHistoryResponse": "The A2A service returned invalid processing history.", "invalidField": "Please check: {{field}}" }
+ "errors": {
+ "invalidResponse": "The A2A service returned an invalid status.",
+ "invalidHistoryResponse": "The A2A service returned invalid processing history.",
+ "invalidField": "Please check: {{field}}"
+ }
},
"offloadFiles": {
"title": "Offload Files",
@@ -1088,7 +1224,10 @@
"memory": { "label": "Memory Sensitive Info Filter", "hint": "Configure sensitive content types forbidden from memory" },
"email": { "label": "Email Settings", "hint": "Email account and token settings" },
"other": { "label": "Other Settings", "hint": "Unclassified extended parameters" },
- "proactive": { "label": "Proactive Recommendation", "hint": "Automatically analyze user needs and proactively offer suggestions; adjust the schedule in the Cron panel" }
+ "proactive": {
+ "label": "Proactive Recommendation",
+ "hint": "Automatically analyze user needs and proactively offer suggestions; adjust the schedule in the Cron panel"
+ }
},
"booleanLabels": {
"evolutionEnabled": "Enable skill self-evolution",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 92752ccfc8..6e325aa737 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -560,33 +560,161 @@
"title": "A2A 调度中心",
"subtitle": "管理 JiuwenSwarm 对外提供的 A2A 服务。",
"tabs": { "ariaLabel": "A2A 调度中心页面", "config": "入站配置", "outbound": "出站配置", "history": "处理历史" },
- "enable": "启用服务", "enabling": "启用中...", "disable": "停用服务", "disabling": "停用中...", "reload": "重新加载", "reloading": "重载中...",
- "save": "保存配置", "saveAndApply": "保存并应用", "applying": "应用中...", "saved": "配置已保存,尚未应用到正在运行的服务。", "savedAndApplied": "配置已保存并应用。",
+ "enable": "启用服务",
+ "enabling": "启用中...",
+ "disable": "停用服务",
+ "disabling": "停用中...",
+ "restart": "重启服务",
+ "restarting": "重启中...",
+ "restartHint": "停止并重新启动入站服务,现有连接可能短暂中断。",
+ "refreshStatus": "刷新状态",
+ "refreshHint": "重新读取当前状态和配置,不会重启服务。",
+ "save": "保存配置",
+ "saveAndApply": "保存并应用",
+ "applying": "应用中...",
+ "saved": "配置已保存,尚未应用到正在运行的服务。",
+ "savedAndApplied": "配置已保存并应用。",
"disconnected": "当前未连接到 Gateway,无法读取或修改 A2A 服务。",
- "saveBeforeLifecycleAction": "配置有未保存的修改,请先保存后再启用、停用或重载服务。",
+ "saveBeforeLifecycleAction": "配置有未保存的修改,请先保存后再启用、停用或重启服务。",
"states": { "disabled": "已关闭", "starting": "启动中", "running": "运行中", "stopping": "停止中", "error": "异常" },
- "status": { "title": "服务状态", "configRevision": "配置版本:{{revision}}", "effectiveRpcUrl": "实际 JSON-RPC 地址", "effectiveCardUrl": "实际 Agent Card 地址", "notListening": "当前未监听" },
+ "status": {
+ "title": "服务状态",
+ "configRevision": "配置版本:{{revision}}",
+ "effectiveRpcUrl": "实际 JSON-RPC 地址",
+ "effectiveCardUrl": "实际 Agent Card 地址",
+ "notListening": "当前未监听"
+ },
"config": { "title": "入站服务配置", "description": "保存只更新目标配置;“保存并应用”会重载正在运行的服务。" },
"outbound": {
- "localDebug": { "title": "本地 Agent 调试", "description": "控制是否允许发现和调用本机 loopback 地址上的明文 HTTP Agent。设置保存后立即生效。", "allow": "允许本机 HTTP Agent", "warning": "仅用于本机 E2E 调试。启用后会放宽针对 127.0.0.1 / ::1 的 SSRF 防护,请勿在生产环境开启。", "saving": "保存中...", "saved": "出站本地调试设置已保存并立即生效。" },
- "discovery": { "title": "发现第三方 Agent", "description": "发现仅获取并预览 Agent Card;完成手动注册后,JiuwenSwarm 才能调用该 Agent。", "action": "发现 Agent", "discovering": "发现中...", "previewOnly": "仅预览,尚未注册", "previewReady": "发现成功。请核对信息并显式注册,当前候选尚不可调用。", "advanced": "高级配置" },
- "list": { "title": "已注册 Agent", "total": "共 {{count}} 个", "empty": "暂无已注册的第三方 Agent" },
- "fields": { "version": "版本", "endpoint": "实际 Endpoint", "protocol": "协议", "expiresAt": "候选过期时间", "displayName": "显示名称", "credential": "API Key / Bearer(可选,不会回显)", "revision": "Card 版本", "credentialState": "凭据", "lastChecked": "最近检查", "connectTimeout": "连接超时(秒)", "syncWait": "同步等待超时(秒)", "replaceCredential": "替换凭据(留空则不修改)" },
+ "localDebug": {
+ "title": "本地 Agent 调试",
+ "description": "控制是否允许发现和调用本机 loopback 地址上的明文 HTTP Agent。设置保存后立即生效。",
+ "allow": "允许本机 HTTP Agent",
+ "warning": "仅用于本机 E2E 调试。启用后会放宽针对 127.0.0.1 / ::1 的 SSRF 防护,请勿在生产环境开启。",
+ "saving": "保存中...",
+ "saved": "出站本地调试设置已保存并立即生效。"
+ },
+ "discovery": {
+ "title": "发现第三方 Agent",
+ "description": "发现仅获取并预览 Agent Card;完成手动注册后,JiuwenSwarm 才能调用该 Agent。",
+ "urlLabel": "Agent Card 地址",
+ "action": "发现 Agent",
+ "discovering": "发现中...",
+ "previewOnly": "仅预览,尚未注册",
+ "previewReady": "发现成功。请核对信息并显式注册,当前候选尚不可调用。",
+ "candidateTitle": "待注册 Agent",
+ "candidateDescription": "核对发现结果并补充注册信息,完成注册后才会加入可调用列表。",
+ "registrationTitle": "注册信息",
+ "registrationDescription": "设置在 JiuwenSwarm 中显示的名称,并按需填写调用凭据。",
+ "advanced": "高级配置"
+ },
+ "list": {
+ "title": "已注册 Agent",
+ "description": "管理第三方 Agent 的可用状态、连接配置和 Card 更新。",
+ "empty": "暂无已注册的第三方 Agent"
+ },
+ "fields": {
+ "version": "版本",
+ "endpoint": "实际 Endpoint",
+ "protocol": "协议",
+ "expiresAt": "候选过期时间",
+ "displayName": "显示名称",
+ "credential": "API Key / Bearer(可选,不会回显)",
+ "revision": "Card 版本",
+ "credentialState": "凭据",
+ "lastChecked": "最近检查",
+ "connectTimeout": "连接超时(秒)",
+ "syncWait": "同步等待超时(秒)",
+ "replaceCredential": "替换凭据(留空则不修改)"
+ },
"availability": { "available": "可用", "unreachable": "不可达", "incompatible": "不兼容", "review_required": "待确认" },
- "register": "注册", "registering": "注册中...", "registered": "第三方 Agent 已注册,现在可按启用和可用状态参与出站调用。",
- "enabled": "已启用", "disabled": "已停用", "enable": "启用", "disable": "停用", "refresh": "刷新 Card",
- "configured": "已配置", "notConfigured": "未配置", "settings": "配置", "saved": "注册项配置已保存。", "clearCredential": "清除已保存凭据", "reviewRequired": "检测到 Endpoint、协议、安全要求或身份信息的关键变化。确认前已暂停新调用。", "endpointChange": "Endpoint 变化",
- "confirm": "确认并应用", "reject": "拒绝变化", "deleteConfirm": "确定删除该注册项吗?已有派发历史会保留,但新调用将立即被拒绝。",
+ "register": "注册",
+ "registering": "注册中...",
+ "registered": "第三方 Agent 已注册,现在可按启用和可用状态参与出站调用。",
+ "enabled": "已启用",
+ "disabled": "已停用",
+ "enable": "启用",
+ "disable": "停用",
+ "refresh": "刷新 Card",
+ "configured": "已配置",
+ "notConfigured": "未配置",
+ "settings": "配置",
+ "saved": "注册项配置已保存。",
+ "clearCredential": "清除已保存凭据",
+ "reviewRequired": "检测到 Endpoint、协议、安全要求或身份信息的关键变化。确认前已暂停新调用。",
+ "endpointChange": "Endpoint 变化",
+ "confirm": "确认并应用",
+ "reject": "拒绝变化",
+ "deleteConfirm": "确定删除该注册项吗?已有派发历史会保留,但新调用将立即被拒绝。",
"errors": { "invalidResponse": "A2A 出站管理服务返回了无效数据。", "invalidSettings": "请填写有效的显示名称和大于 0 的超时时间。" }
},
"history": {
- "title": "入向请求处理历史", "description": "显示当前 Gateway 进程内最近 200 条 A2A 入向请求,不记录请求正文。", "total": "共 {{count}} 条", "empty": "暂无处理记录", "emptyDescription": "收到 A2A 入向请求后,处理状态会显示在这里。", "processing": "处理中",
+ "tabs": { "ariaLabel": "A2A 请求处理历史类型", "ingress": "入站请求", "outbound": "出站请求" },
+ "copy": "点击复制",
+ "copied": "已复制",
+ "copyFailed": "复制失败,请检查浏览器剪贴板权限。",
+ "ingress": {
+ "title": "入站请求处理历史",
+ "description": "显示当前 Gateway 进程内最近 200 条 A2A 入站请求,不记录请求正文。",
+ "empty": "暂无入站处理记录",
+ "emptyDescription": "收到 A2A 入站请求后,处理状态会显示在这里。"
+ },
+ "outbound": {
+ "title": "出站请求处理历史",
+ "description": "显示最近 200 条 A2A 出站派发记录,不展示请求正文或响应正文。",
+ "empty": "暂无出站处理记录",
+ "emptyDescription": "向第三方 Agent 派发请求后,处理状态会显示在这里。",
+ "modes": { "sync": "同步", "async": "异步" },
+ "statuses": {
+ "created": "已创建",
+ "submitting": "提交中",
+ "accepted": "已接收",
+ "working": "执行中",
+ "completed": "已完成",
+ "failed": "失败",
+ "canceled": "已取消",
+ "rejected": "已拒绝",
+ "input_required": "等待输入",
+ "auth_required": "需要认证",
+ "unknown": "状态未知",
+ "timed_out": "已超时",
+ "dispatch_failed": "派发失败"
+ }
+ },
+ "processing": "处理中",
"statuses": { "processing": "处理中", "completed": "已完成", "failed": "失败", "canceled": "已取消" },
"operations": { "message": "消息处理" },
- "columns": { "status": "状态", "operation": "请求类型", "requestId": "请求 ID", "contextId": "上下文 ID", "startedAt": "开始时间", "duration": "耗时", "error": "错误信息" }
+ "columns": {
+ "status": "状态",
+ "operation": "请求类型",
+ "requestId": "请求 ID",
+ "contextId": "上下文 ID",
+ "mode": "模式",
+ "agentId": "Agent ID",
+ "dispatchId": "派发 ID",
+ "remoteTaskId": "远端任务 ID",
+ "startedAt": "开始时间",
+ "duration": "耗时",
+ "error": "错误信息"
+ }
},
- "fields": { "host": "监听地址", "port": "监听端口", "rpc_path": "RPC 路径", "card_path": "Agent Card 路径", "extended_card_path": "扩展 Card 路径", "protocol_version": "协议版本", "app_name": "Agent 名称", "app_description": "Agent 描述", "app_version": "Agent 版本", "expose_reasoning": "在 A2A 响应中暴露 reasoning" },
- "errors": { "invalidResponse": "A2A 服务返回了无效状态。", "invalidHistoryResponse": "A2A 服务返回了无效的处理历史。", "invalidField": "请检查字段:{{field}}" }
+ "fields": {
+ "host": "监听地址",
+ "port": "监听端口",
+ "rpc_path": "RPC 路径",
+ "card_path": "Agent Card 路径",
+ "extended_card_path": "扩展 Card 路径",
+ "protocol_version": "协议版本",
+ "app_name": "Agent 名称",
+ "app_description": "Agent 描述",
+ "app_version": "Agent 版本",
+ "expose_reasoning": "在 A2A 响应中暴露 reasoning"
+ },
+ "errors": {
+ "invalidResponse": "A2A 服务返回了无效状态。",
+ "invalidHistoryResponse": "A2A 服务返回了无效的处理历史。",
+ "invalidField": "请检查字段:{{field}}"
+ }
},
"offloadFiles": {
"title": "离线文件",
diff --git a/jiuwenswarm/channels/web/frontend/tests/a2aIngressPanelState.test.mjs b/jiuwenswarm/channels/web/frontend/tests/a2aIngressPanelState.test.mjs
index 5a3a5706de..1c165fcd96 100644
--- a/jiuwenswarm/channels/web/frontend/tests/a2aIngressPanelState.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/a2aIngressPanelState.test.mjs
@@ -5,6 +5,7 @@ import {
draftFromA2AIngressSnapshot,
isA2AIngressTransitioning,
normalizeA2AIngressHistory,
+ normalizeA2AOutboundDispatchHistory,
normalizeA2AIngressSnapshot,
shouldAcceptA2AIngressResponse,
toA2AIngressPatch,
@@ -93,18 +94,102 @@ test('A2A ingress ignores obsolete refresh responses', () => {
});
test('A2A ingress history accepts lifecycle metadata and rejects malformed rows', () => {
- assert.deepEqual(normalizeA2AIngressHistory({
- items: [{
- request_id: 'req-1', context_id: 'ctx-1', message_id: 'msg-1', operation: 'message',
- status: 'completed', started_at: 10, finished_at: 10.2, duration_ms: 200, error: null,
- }],
- total: 1,
- }), {
- items: [{
- request_id: 'req-1', context_id: 'ctx-1', message_id: 'msg-1', operation: 'message',
- status: 'completed', started_at: 10, finished_at: 10.2, duration_ms: 200, error: null,
- }],
- total: 1,
- });
+ assert.deepEqual(
+ normalizeA2AIngressHistory({
+ items: [
+ {
+ request_id: 'req-1',
+ context_id: 'ctx-1',
+ message_id: 'msg-1',
+ operation: 'message',
+ status: 'completed',
+ started_at: 10,
+ finished_at: 10.2,
+ duration_ms: 200,
+ error: null,
+ },
+ ],
+ total: 1,
+ }),
+ {
+ items: [
+ {
+ request_id: 'req-1',
+ context_id: 'ctx-1',
+ message_id: 'msg-1',
+ operation: 'message',
+ status: 'completed',
+ started_at: 10,
+ finished_at: 10.2,
+ duration_ms: 200,
+ error: null,
+ },
+ ],
+ total: 1,
+ },
+ );
assert.equal(normalizeA2AIngressHistory({ items: [{ request_id: '', status: 'completed' }] }), null);
});
+
+test('A2A outbound history accepts dispatch metadata without result bodies', () => {
+ assert.deepEqual(
+ normalizeA2AOutboundDispatchHistory({
+ items: [
+ {
+ dispatch_id: 'disp-1',
+ agent_id: 'agent-1',
+ mode: 'sync',
+ status: 'completed',
+ remote_task_id: 'task-1',
+ created_at: '2026-08-27T01:00:00Z',
+ updated_at: '2026-08-27T01:00:02Z',
+ accepted_at: '2026-08-27T01:00:01Z',
+ finished_at: '2026-08-27T01:00:02Z',
+ error_code: null,
+ error_summary: null,
+ },
+ ],
+ total: 1,
+ }),
+ {
+ items: [
+ {
+ dispatch_id: 'disp-1',
+ agent_id: 'agent-1',
+ mode: 'sync',
+ status: 'completed',
+ remote_task_id: 'task-1',
+ created_at: '2026-08-27T01:00:00Z',
+ updated_at: '2026-08-27T01:00:02Z',
+ accepted_at: '2026-08-27T01:00:01Z',
+ finished_at: '2026-08-27T01:00:02Z',
+ error_code: null,
+ error_summary: null,
+ },
+ ],
+ total: 1,
+ },
+ );
+});
+
+test('A2A outbound history skips malformed rows without discarding valid records', () => {
+ const history = normalizeA2AOutboundDispatchHistory({
+ items: [
+ { dispatch_id: 'bad-status', agent_id: 'agent-1', mode: 'sync', status: 'future_status', created_at: '2026-08-27T01:00:00Z' },
+ {
+ dispatch_id: 'disp-1',
+ agent_id: 'agent-1',
+ mode: 'async',
+ status: 'timed_out',
+ created_at: '2026-08-27T01:00:00Z',
+ updated_at: '2026-08-27T01:00:10Z',
+ },
+ ],
+ total: 2,
+ });
+
+ assert.equal(history?.items.length, 1);
+ assert.equal(history?.items[0].dispatch_id, 'disp-1');
+ assert.equal(history?.items[0].updated_at, '2026-08-27T01:00:10Z');
+ assert.equal(history?.total, 2);
+});
diff --git a/jiuwenswarm/gateway/a2a_manager/manager.py b/jiuwenswarm/gateway/a2a_manager/manager.py
index fbd5a732ee..edeffb4fcc 100644
--- a/jiuwenswarm/gateway/a2a_manager/manager.py
+++ b/jiuwenswarm/gateway/a2a_manager/manager.py
@@ -175,6 +175,9 @@ class A2AManager:
async def outbound_dispatch_get(self, dispatch_id: str) -> dict[str, Any]:
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)
+
async def outbound_find_agents(
self,
*,
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
index b0f7b24bb7..bcfcc46559 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/dispatcher.py
@@ -404,7 +404,10 @@ class A2AOutboundDispatcher:
parts=[Part(text=task_text)],
),
configuration=SendMessageConfiguration(
- return_immediately=dispatch.mode is A2AOutboundDispatchMode.ASYNC
+ # Both modes need the remote acceptance/rejection result promptly.
+ # Sync mode waits locally by polling the accepted task below instead
+ # of asking the remote HTTP request to stay open for the whole task.
+ return_immediately=True
),
)
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py
index a4de234e87..44f1d73a6f 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/registry.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/registry.py
@@ -415,6 +415,29 @@ class A2AOutboundRegistry:
raise A2AOutboundError(A2AOutboundErrorCode.DISPATCH_NOT_FOUND)
return item.to_record()
+ async def list_dispatches(self, *, limit: int = 200) -> 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()
+ items = []
+ for item in records:
+ items.append(
+ {
+ "dispatch_id": item.dispatch_id,
+ "agent_id": item.agent_id,
+ "mode": item.mode.value,
+ "status": item.status.value,
+ "remote_task_id": item.remote_task_id,
+ "created_at": item.created_at,
+ "updated_at": item.updated_at,
+ "accepted_at": item.accepted_at,
+ "finished_at": item.finished_at,
+ "error_code": item.error_code,
+ "error_summary": item.error_summary,
+ }
+ )
+ return {"items": items, "total": total}
+
async def _require_agent(self, agent_id: str) -> A2AOutboundAgent:
item = await self._repository.get_agent(str(agent_id or "").strip())
if item is None:
diff --git a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py b/jiuwenswarm/gateway/a2a_manager/outbound/repository.py
index 01413108cc..a92f0432de 100644
--- a/jiuwenswarm/gateway/a2a_manager/outbound/repository.py
+++ b/jiuwenswarm/gateway/a2a_manager/outbound/repository.py
@@ -216,6 +216,14 @@ class A2AOutboundRepository:
)
return [self._codec.dispatch_from_record(row) for row in rows]
+ async def count_dispatches(self) -> 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(),
+ )
+ return len(rows)
+
async def create_dispatch(
self,
dispatch: A2AOutboundDispatch,
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 94e322161d..fb790f30ef 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -1879,6 +1879,25 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
lambda: a2a_manager.outbound_dispatch_get(str(params.get("dispatch_id") or "")),
)
+ async def _a2a_outbound_dispatch_list(ws, req_id, params, session_id):
+ try:
+ limit = int(params.get("limit", 200))
+ except (TypeError, ValueError):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="limit must be an integer",
+ code="A2A_OUTBOUND_STORE_INVALID",
+ )
+ return
+ limit = max(1, min(limit, 200))
+ await _send_a2a_outbound(
+ ws,
+ req_id,
+ lambda: a2a_manager.outbound_dispatch_list(limit=limit),
+ )
+
channel.register_method("a2a.outbound.settings.get", _a2a_outbound_settings_get)
channel.register_method("a2a.outbound.settings.update", _a2a_outbound_settings_update)
channel.register_method("a2a.outbound.discover", _a2a_outbound_discover)
@@ -1891,6 +1910,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
"a2a.outbound.confirm_revision", _a2a_outbound_confirm_revision
)
channel.register_method("a2a.outbound.delete", _a2a_outbound_delete)
+ channel.register_method("a2a.outbound.dispatch.list", _a2a_outbound_dispatch_list)
channel.register_method("a2a.outbound.dispatch.get", _a2a_outbound_dispatch_get)
from jiuwenswarm.common.schema.message import Message, EventType
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py
index 467dbf4e14..789ee7f233 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_routes.py
@@ -166,6 +166,14 @@ _A2A_OUTBOUND_ROUTES: tuple[WebHttpMappedRoute, ...] = (
"删除第三方 A2A Agent 注册项",
path_to_param={"agent_id": "agent_id"},
),
+ WebHttpMappedRoute(
+ "GET",
+ "/a2a/outbound/dispatches",
+ "a2a.outbound.dispatch.list",
+ "a2a",
+ "列出 A2A 出站派发处理历史",
+ query_keys=("limit",),
+ ),
WebHttpMappedRoute(
"GET",
"/a2a/outbound/dispatches/{dispatch_id}",
diff --git a/jiuwenswarm/gateway/routing/http_agent_client.py b/jiuwenswarm/gateway/routing/http_agent_client.py
index d92ed17c56..92f9089599 100644
--- a/jiuwenswarm/gateway/routing/http_agent_client.py
+++ b/jiuwenswarm/gateway/routing/http_agent_client.py
@@ -381,7 +381,12 @@ class HttpSseAgentServerClient(AgentServerClient):
try:
http = self._ensure_http()
timeout = httpx.Timeout(None, connect=_CONNECT_TIMEOUT_SECONDS)
- async with http.stream("GET", url, timeout=timeout) as response:
+ async with http.stream(
+ "GET",
+ url,
+ headers={"X-Jiuwen-Push-Consumer": "gateway"},
+ timeout=timeout,
+ ) as response:
response.raise_for_status()
async for frame in iter_sse_data_frames(response):
meta = frame.get("metadata")
diff --git a/jiuwenswarm/server/agent_http_routes.py b/jiuwenswarm/server/agent_http_routes.py
index 440e3e8017..c379ed7786 100644
--- a/jiuwenswarm/server/agent_http_routes.py
+++ b/jiuwenswarm/server/agent_http_routes.py
@@ -629,6 +629,11 @@ def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:
qp = request.query_params
session_filter = qp.get("session_id") or ctx.session_id
channel_filter = qp.get("channel_id")
+ # 信任边界假设:此头仅由内部 Gateway 设置,可被伪造;若端点可能暴露给
+ # 不受信任客户端,需改用 mTLS/共享密钥等强验证。
+ reverse_rpc_capable = (
+ request.headers.get("x-jiuwen-push-consumer") == "gateway"
+ )
registry = get_push_registry()
sink = SSESink()
@@ -648,7 +653,11 @@ def _register_special_routes(app: Any, server: AgentHTTPServer) -> None:
# 填满 maxsize 后,`PushRegistry.push` 每次扇到它都要等满超时才注销 ——
# 进程级推送被一个早已消失的客户端拖累。
registry.register(
- subscriber_id, sink, session_id=session_filter, channel_id=channel_filter
+ subscriber_id,
+ sink,
+ session_id=session_filter,
+ channel_id=channel_filter,
+ reverse_rpc_capable=reverse_rpc_capable,
)
try:
while True:
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 51ed355fe0..2a75683501 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -35,6 +35,7 @@ from jiuwenswarm.common.e2a.agent_compat import e2a_to_agent_request
from jiuwenswarm.common.e2a.constants import (
E2A_CANCEL_SOURCE_CLIENT_DISCONNECT,
E2A_INTERNAL_CANCEL_SOURCE_KEY,
+ E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST,
E2A_WIRE_INTERNAL_METADATA_KEYS,
)
from jiuwenswarm.common.e2a.gateway_normalize import (
@@ -343,6 +344,11 @@ class AgentWebSocketServer:
get_acp_output_manager().set_send_push_callback(
lambda msg: asyncio.create_task(self.send_push(msg))
)
+ get_push_registry().set_reverse_rpc_owner_lost_callback(
+ lambda: get_acp_output_manager().fail_pending_requests(
+ RuntimeError("Gateway reverse RPC connection lost")
+ )
+ )
def set_proactive_engine(self, engine: Any) -> None:
"""Store the proactive engine instance for debug trigger interface."""
@@ -826,6 +832,7 @@ class AgentWebSocketServer:
push_subscriber_id,
_GatewayWSPushSink(ws, send_lock),
drop_on_stall=False,
+ reverse_rpc_capable=True,
)
# 触发身份获取(写入当前连接 context;无 provider 时身份为 null,连接继续)。
@@ -1182,7 +1189,13 @@ class AgentWebSocketServer:
应用此返回值判定成败,勿再把「仅打了 warning」当成发送成功。
"""
registry = get_push_registry()
- if registry.subscriber_count() == 0:
+ response_kind = str(msg.get("response_kind") or "").strip()
+ is_reverse_rpc = response_kind == E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST
+ if (
+ not registry.reverse_rpc_ready()
+ if is_reverse_rpc
+ else registry.subscriber_count() == 0
+ ):
# 一个去处都没有:保持原有告警与早退(连 wire 都不构造)。
logger.warning(
"[AgentWebSocketServer] send_push 失败: 无活跃 Gateway 连接 "
@@ -1201,7 +1214,11 @@ class AgentWebSocketServer:
logger.warning("[AgentWebSocketServer] send_push 失败: %s", e)
return 0
- delivered = await registry.push(wire)
+ delivered = (
+ await registry.push_reverse_rpc(wire)
+ if is_reverse_rpc
+ else await registry.push(wire)
+ )
if delivered == 0:
# 两种情况都会落到这里:内容过大被降级成错误帧(sink 返回 False),
@@ -1213,7 +1230,6 @@ class AgentWebSocketServer:
)
return 0
- response_kind = str(msg.get("response_kind") or "").strip()
if response_kind:
logger.info(
"[AgentWebSocketServer] send_push response_kind wire sent: "
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 2036d6963a..4a15ddcdbc 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -67,6 +67,7 @@ from jiuwenswarm.agents.harness.common.rails import (
StructuredAskUserRail,
)
from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode, is_memory_enabled
+from jiuwenswarm.common.local_env_config import is_enterprise
from jiuwenswarm.agents.harness.common.tools import (
SkillToolkit,
)
@@ -490,7 +491,12 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
# 权限护栏由 openjiuwen PermissionInterruptRail + ToolPermissionHost 接管;
# 无需初始化 jiuwenswarm 内置 PermissionEngine(已弃用)。
- rails_list = self._build_agent_rails(config, config_base, mode="code")
+ rails_list = self._build_agent_rails(
+ config,
+ config_base,
+ mode=mode,
+ sub_mode=sub_mode,
+ )
sys_operation = self._create_sys_operation()
if sys_operation is None:
@@ -601,6 +607,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
config_base: dict[str, Any],
*,
mode: str = "code",
+ sub_mode: str | None = None,
) -> list[Any]:
"""Build rails for code mode: fixed rails + dynamic rails from config.
@@ -663,6 +670,21 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
_RailBuildInfo("_code_plan_approval_rail", self._build_plan_approval_rail),
]
+ normalized_sub_mode = str(sub_mode or "normal").strip().lower() or "normal"
+ # The CodeAdapter may be rebuilt through JiuWenSwarm.create_instance(),
+ # whose compatibility default is mode="agent" even when this adapter
+ # already owns a Code session. Sub-mode is the reliable profile key:
+ # normal/plan are single-Agent, while Team profiles are assembled by
+ # the declarative swarm provider and must not register this rail twice.
+ if normalized_sub_mode in {"normal", "plan"} and not is_enterprise():
+ # Append, don't insert at a fixed index, to avoid silent misplacement.
+ rail_infos.append(
+ _RailBuildInfo(
+ "_a2a_outbound_toolkit_rail",
+ self._build_a2a_outbound_toolkit_rail,
+ ),
+ )
+
# 动态 Rails — 从 config.yaml::modes.code.rails 读取
# 跳过已在固定列表中的 rail,避免重复注册
configured_rails = mode_config.get("rails") or []
@@ -1573,7 +1595,12 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
self._agent_workspace_dir,
)
- rails = self._build_agent_rails(react_config, config_base, mode="code")
+ rails = self._build_agent_rails(
+ react_config,
+ config_base,
+ mode="code",
+ sub_mode="team",
+ )
added_rails = sum(1 for rail in rails if _queue_rail_if_missing(agent, rail))
subagents, _should_add_general = self._build_configured_subagents(model, react_config, config_base)
diff --git a/jiuwenswarm/server/transports/push_registry.py b/jiuwenswarm/server/transports/push_registry.py
index 5bfb3282b5..28495a120f 100644
--- a/jiuwenswarm/server/transports/push_registry.py
+++ b/jiuwenswarm/server/transports/push_registry.py
@@ -15,8 +15,13 @@ WS 侧语义(2026-08 起)
全局 id 无条件清空(旧单槽位曾导致:短连接覆盖后断开 → 长连接仍在收请求流、
但 ``send_push`` 永久失败,前端收不到 ``chat.file`` 且工具误报成功)。
-历史:固定 id ``gateway-ws`` 单槽 + 断开无条件清空,真机出现过「短连接挤掉长连接
-后永久无推送」。``WS_PUSH_SUBSCRIBER_ID`` 常量仅作前缀/兼容别名保留。
+2026-08-20 真机实测过旧单槽位方案的杀伤力:几条只活 5 秒的短连接轮流接入/断开,
+把长连接挤出槽位后又清空;长连接因为一直没断**不会重新注册**,于是前端**永久收
+不到推送且毫无报错**,只能重启服务恢复(刷新浏览器无效)。``WS_PUSH_SUBSCRIBER_ID``
+常量仅作前缀/兼容别名保留,不要再拿它当全局单槽注册。
+
+反向 RPC 另有一个显式 owner。普通推送仍按原语义扇出;ACP/A2A 请求只投递给
+最后注册的 RPC-capable Gateway,避免多个 SSE 订阅者重复执行同一个工具请求。
与 ``server.gateway_push`` 的区别(名字相近,角色相反)
--------------------------------------------------
@@ -34,6 +39,7 @@ from __future__ import annotations
import asyncio
import logging
+from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
@@ -100,10 +106,26 @@ class _Subscriber:
class PushRegistry:
"""推送订阅者注册表:把「推给当前连接」变成「推给匹配的订阅者」。"""
- __slots__ = ("_subscribers",)
+ __slots__ = (
+ "_reverse_rpc_owner_id",
+ "_reverse_rpc_owner_lost_callback",
+ "_subscribers",
+ )
def __init__(self) -> None:
self._subscribers: dict[str, _Subscriber] = {}
+ self._reverse_rpc_owner_id: str | None = None
+ self._reverse_rpc_owner_lost_callback: Callable[[], None] | None = None
+
+ def set_reverse_rpc_owner_lost_callback(
+ self, callback: Callable[[], None] | None
+ ) -> None:
+ self._reverse_rpc_owner_lost_callback = callback
+
+ def _notify_reverse_rpc_owner_lost(self) -> None:
+ callback = self._reverse_rpc_owner_lost_callback
+ if callback is not None:
+ callback()
def register(
self,
@@ -113,19 +135,32 @@ class PushRegistry:
session_id: str | None = None,
channel_id: str | None = None,
drop_on_stall: bool = True,
+ reverse_rpc_capable: bool = False,
) -> None:
"""登记一个订阅者。同 ``subscriber_id`` 重复注册会覆盖旧的。
``drop_on_stall`` 的含义见 :class:`_Subscriber` —— WS 侧必须传 ``False``。
+
+ ``reverse_rpc_capable=True`` 使此订阅者成为反向 RPC owner;调用方需
+ 自行确保该标记来自可信来源。
"""
+ replacing_rpc_owner = self._reverse_rpc_owner_id == subscriber_id
self._subscribers[subscriber_id] = _Subscriber(
sink=sink,
session_id=session_id,
channel_id=channel_id,
drop_on_stall=drop_on_stall,
)
+ if reverse_rpc_capable:
+ if self._reverse_rpc_owner_id is not None:
+ self._notify_reverse_rpc_owner_lost()
+ self._reverse_rpc_owner_id = subscriber_id
+ elif replacing_rpc_owner:
+ self._reverse_rpc_owner_id = None
+ self._notify_reverse_rpc_owner_lost()
logger.info(
- "[PushRegistry] 订阅者接入: id=%s session_id=%s channel_id=%s 当前订阅数=%d",
+ "[PushRegistry] 订阅者接入: id=%s session_id=%s "
+ "channel_id=%s 当前订阅数=%d",
subscriber_id,
session_id,
channel_id,
@@ -135,6 +170,9 @@ class PushRegistry:
def unregister(self, subscriber_id: str) -> None:
"""注销订阅者。不存在时静默返回(断连清理可能重入)。"""
if self._subscribers.pop(subscriber_id, None) is not None:
+ if self._reverse_rpc_owner_id == subscriber_id:
+ self._reverse_rpc_owner_id = None
+ self._notify_reverse_rpc_owner_lost()
logger.info(
"[PushRegistry] 订阅者断开: id=%s 当前订阅数=%d",
subscriber_id,
@@ -144,6 +182,41 @@ class PushRegistry:
def subscriber_count(self) -> int:
return len(self._subscribers)
+ def reverse_rpc_ready(self) -> bool:
+ owner_id = self._reverse_rpc_owner_id
+ return owner_id is not None and owner_id in self._subscribers
+
+ async def push_reverse_rpc(self, wire: dict[str, Any]) -> int:
+ """Deliver a point-to-point reverse RPC to the current Gateway owner."""
+ owner_id = self._reverse_rpc_owner_id
+ subscriber = self._subscribers.get(owner_id or "")
+ if owner_id is None or subscriber is None or not subscriber.matches(wire):
+ return 0
+ try:
+ if subscriber.drop_on_stall:
+ sent = await asyncio.wait_for(
+ subscriber.sink.send_wire(wire), timeout=SEND_TIMEOUT
+ )
+ else:
+ sent = await subscriber.sink.send_wire(wire)
+ except TimeoutError:
+ logger.warning(
+ "[PushRegistry] 反向 RPC 推送超时(%.1fs),注销订阅者: id=%s",
+ SEND_TIMEOUT,
+ owner_id,
+ )
+ self.unregister(owner_id)
+ return 0
+ except Exception as exc: # noqa: BLE001 - owner loss fails pending RPCs
+ logger.warning(
+ "[PushRegistry] 反向 RPC 推送失败,注销订阅者: id=%s error=%s",
+ owner_id,
+ exc,
+ )
+ self.unregister(owner_id)
+ return 0
+ return int(bool(sent))
+
async def push(self, wire: dict[str, Any]) -> int:
"""向匹配的订阅者扇出一条已构造好的 wire 帧。
diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.py
index f8404984cd..c59424b478 100644
--- a/tests/agents/swarm/test_swarm_assembly.py
+++ b/tests/agents/swarm/test_swarm_assembly.py
@@ -84,6 +84,7 @@ from jiuwenswarm.common.coding_memory_paths import (
resolve_project_coding_memory_workspace_path,
)
from jiuwenswarm.common.config import get_config
+from jiuwenswarm.server.runtime.agent_adapter import interface_deep
logger = logging.getLogger(__name__)
@@ -97,6 +98,58 @@ def test_member_runtime_prompt_rail_binds_request_identity(mode: str) -> None:
assert rail._session_id == "session-123"
assert rail._mode == mode
+
[email protected]("mode", ["team", "code.team", "team.plan"])
+def test_team_a2a_outbound_rail_binds_request_route(mode: str, monkeypatch) -> None:
+ monkeypatch.delenv("AGENT_RUNTIME", raising=False)
+ monkeypatch.setattr(interface_deep, "get_runtime_tool_session_id", lambda: None)
+ monkeypatch.setattr(interface_deep, "get_runtime_tool_channel_id", lambda: "default")
+ context = SwarmBuildContext(
+ session_id="session-a2a",
+ channel="web",
+ mode=mode,
+ )
+
+ rail = RailSpec(type=registry.A2A_OUTBOUND_TOOLKIT).build(
+ language="cn",
+ context=context,
+ )
+
+ assert rail is not None
+ assert rail._runtime_route() == ("session-a2a", "web")
+
+
+def test_team_a2a_outbound_rail_uses_live_route_when_context_session_is_empty(
+ monkeypatch,
+) -> None:
+ monkeypatch.delenv("AGENT_RUNTIME", raising=False)
+ monkeypatch.setattr(
+ interface_deep,
+ "get_runtime_tool_session_id",
+ lambda: "live-session",
+ )
+ monkeypatch.setattr(
+ interface_deep,
+ "get_runtime_tool_channel_id",
+ lambda: "live-channel",
+ )
+ context = SwarmBuildContext(session_id="", channel="web", mode="team")
+
+ rail = RailSpec(type=registry.A2A_OUTBOUND_TOOLKIT).build(
+ language="cn",
+ context=context,
+ )
+
+ assert rail is not None
+ assert rail._runtime_route() == ("live-session", "live-channel")
+
+
+def test_team_a2a_outbound_rail_is_excluded_from_enterprise_runtime(monkeypatch) -> None:
+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
+ context = SwarmBuildContext(session_id="session-a2a", channel="web")
+
+ assert member_rails._build_a2a_outbound_toolkit_rail({}, context) is None
+
# Rail provider names shared by both roles (no role-specific evolution rails).
# Harness todo planning is teammate-only; leaders use the team task board instead.
# Sourced from the registry symbols so the test tracks renames automatically.
@@ -116,6 +169,7 @@ _TEAM_SHARED_RAIL_NAMES: frozenset[str] = frozenset(
registry.PLUGIN_RAILS,
registry.SKILL_RETRIEVAL_PROMPT,
registry.SYMPHONY_ORCHESTRATION_PROMPT,
+ registry.A2A_OUTBOUND_TOOLKIT,
registry.MEMBER_SKILL_TOOLKIT,
registry.DISABLED_TOOLS,
}
@@ -432,7 +486,7 @@ def test_build_member_capability_specs_rail_names(
assert _TEAM_SHARED_RAIL_NAMES <= rail_names
assert extra_rails <= rail_names
- assert len(_TEAM_SHARED_RAIL_NAMES) == 16
+ assert len(_TEAM_SHARED_RAIL_NAMES) == 17
assert rail_names == expected
disabled_tools = next(
spec for spec in rails_specs if spec.type == registry.DISABLED_TOOLS
@@ -1686,6 +1740,7 @@ _EXPECTED_CODE_RAIL_NAMES_LEADER: frozenset[str] = frozenset(
registry.CODE_SKILL_USE,
registry.SKILL_RETRIEVAL_PROMPT,
registry.SYMPHONY_ORCHESTRATION_PROMPT,
+ registry.A2A_OUTBOUND_TOOLKIT,
registry.CODE_CONFIRM_INTERRUPT,
registry.MEMBER_SKILL_TOOLKIT,
registry.TEAM_WORKSPACE_REPORT_PATH,
diff --git a/tests/transport/test_push_registry.py b/tests/transport/test_push_registry.py
index f653ad641a..c59f05d12c 100644
--- a/tests/transport/test_push_registry.py
+++ b/tests/transport/test_push_registry.py
@@ -116,6 +116,40 @@ def test_push_with_no_subscribers_is_noop() -> None:
assert asyncio.run(PushRegistry().push(_wire())) == 0
+def test_reverse_rpc_uses_only_declared_owner() -> None:
+ reg = PushRegistry()
+ ordinary, gateway = _RecordingSink(), _RecordingSink()
+ reg.register("ordinary", ordinary)
+ reg.register("gateway", gateway, reverse_rpc_capable=True)
+
+ assert reg.reverse_rpc_ready() is True
+ assert asyncio.run(reg.push_reverse_rpc(_wire())) == 1
+ assert ordinary.wires == []
+ assert len(gateway.wires) == 1
+
+
+def test_reverse_rpc_owner_replacement_fails_existing_requests() -> None:
+ reg = PushRegistry()
+ owner_losses = []
+ reg.set_reverse_rpc_owner_lost_callback(lambda: owner_losses.append(True))
+ first, second = _RecordingSink(), _RecordingSink()
+ reg.register("first", first, reverse_rpc_capable=True)
+ reg.register("second", second, reverse_rpc_capable=True)
+
+ assert owner_losses == [True]
+ assert asyncio.run(reg.push_reverse_rpc(_wire())) == 1
+ assert first.wires == []
+ assert len(second.wires) == 1
+
+
+def test_ordinary_subscriber_does_not_make_reverse_rpc_ready() -> None:
+ reg = PushRegistry()
+ reg.register("ordinary", _RecordingSink())
+
+ assert reg.reverse_rpc_ready() is False
+ assert asyncio.run(reg.push_reverse_rpc(_wire())) == 0
+
+
def test_send_push_reaches_http_subscriber_without_ws() -> None:
from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
from jiuwenswarm.server.transports.push_registry import get_push_registry
diff --git a/tests/unit_tests/agentserver/test_code_adapter_a2a_outbound_rail.py b/tests/unit_tests/agentserver/test_code_adapter_a2a_outbound_rail.py
new file mode 100644
index 0000000000..dae40c62e3
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_code_adapter_a2a_outbound_rail.py
@@ -0,0 +1,59 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Code-mode registration coverage for the A2A outbound toolkit rail."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+import openjiuwen.agent_evolving.trajectory as _trajectory_module
+import pytest
+
+if not hasattr(_trajectory_module, "InMemoryTrajectoryRegistry"):
+ _trajectory_module.InMemoryTrajectoryRegistry = MagicMock
+
+from jiuwenswarm.server.runtime.agent_adapter.interface_code import (
+ JiuwenSwarmCodeAdapter,
+)
+
+
+def _rail_attr_names(*, mode: str = "code", sub_mode: str | None = None) -> list[str]:
+ adapter = JiuwenSwarmCodeAdapter()
+ real_instantiate = adapter._instantiate_rails
+
+ def _passthrough_instantiate(rail_infos, _config_base):
+ return rail_infos
+
+ object.__setattr__(adapter, "_instantiate_rails", _passthrough_instantiate)
+ try:
+ rail_infos = adapter._build_agent_rails(
+ config={},
+ config_base={},
+ mode=mode,
+ sub_mode=sub_mode,
+ )
+ finally:
+ object.__setattr__(adapter, "_instantiate_rails", real_instantiate)
+ return [rail_info.attr_name for rail_info in rail_infos]
+
+
[email protected]("sub_mode", [None, "normal", "plan", " "])
+def test_code_single_agent_modes_include_a2a_outbound_rail(sub_mode):
+ assert "_a2a_outbound_toolkit_rail" in _rail_attr_names(sub_mode=sub_mode)
+
+
+def test_code_adapter_default_mode_reload_keeps_a2a_outbound_rail():
+ assert "_a2a_outbound_toolkit_rail" in _rail_attr_names(
+ mode="agent",
+ sub_mode=None,
+ )
+
+
[email protected]("sub_mode", ["team", "TEAM", " team "])
+def test_code_team_modes_exclude_adapter_owned_a2a_outbound_rail(sub_mode):
+ assert "_a2a_outbound_toolkit_rail" not in _rail_attr_names(sub_mode=sub_mode)
+
+
+def test_enterprise_code_mode_excludes_a2a_outbound_rail(monkeypatch):
+ monkeypatch.setenv("JIUWENSWARM_EDITION", "enterprise")
+ assert "_a2a_outbound_toolkit_rail" not in _rail_attr_names(sub_mode="normal")
diff --git a/tests/unit_tests/agentserver/test_team_manager_skill_state.py b/tests/unit_tests/agentserver/test_team_manager_skill_state.py
index cc8524e6a2..9a1e5dc1d4 100644
--- a/tests/unit_tests/agentserver/test_team_manager_skill_state.py
+++ b/tests/unit_tests/agentserver/test_team_manager_skill_state.py
@@ -48,7 +48,7 @@ def test_configure_code_team_member_uses_agent_workspace_coding_memory_path(monk
monkeypatch.setattr(
interface_code.JiuwenSwarmCodeAdapter,
"_build_agent_rails",
- lambda self, react_config, config_base, mode: [],
+ lambda self, react_config, config_base, *, mode="code", sub_mode=None: [],
)
monkeypatch.setattr(
interface_code.JiuwenSwarmCodeAdapter,
diff --git a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py
index 2a762b983b..e011675300 100644
--- a/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py
+++ b/tests/unit_tests/gateway/test_a2a_manager_web_handlers.py
@@ -78,6 +78,9 @@ class _OutboundRegistryProbe:
async def get_dispatch(self, dispatch_id):
return {"dispatch_id": dispatch_id}
+ async def list_dispatches(self, *, limit=200):
+ return {"items": [], "total": 0, "limit": limit}
+
class _OutboundSettingsProbe:
def __init__(self) -> None:
@@ -260,6 +263,9 @@ async def test_a2a_outbound_web_handlers_expose_management_facade():
await channel.methods["a2a.outbound.settings.update"](
object(), "settings-update", {"allow_loopback_http": True}, "session"
)
+ await channel.methods["a2a.outbound.dispatch.list"](
+ object(), "dispatch-list", {"limit": 20}, "session"
+ )
assert channel.responses[0]["payload"]["discovery_id"] == "disc-1"
assert channel.responses[1]["payload"]["agent_id"] == "agent-1"
@@ -272,10 +278,54 @@ async def test_a2a_outbound_web_handlers_expose_management_facade():
assert channel.responses[8]["payload"]["dispatch_id"] == "dispatch-1"
assert channel.responses[9]["payload"] == {"allow_loopback_http": False}
assert channel.responses[10]["payload"] == {"allow_loopback_http": True}
+ assert channel.responses[11]["payload"] == {"items": [], "total": 0, "limit": 20}
assert settings.enabled is True
assert all(item["ok"] for item in channel.responses)
+async def test_a2a_outbound_dispatch_list_rejects_non_integer_limit():
+ channel = _WebChannelProbe()
+ manager = A2AManager(
+ _ChannelManagerProbe(),
+ object(),
+ A2AIngressConfig(),
+ repository=_RepositoryProbe(),
+ channel_factory=lambda config, router: _ChannelProbe(),
+ outbound_registry=_OutboundRegistryProbe(),
+ )
+ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))
+
+ await channel.methods["a2a.outbound.dispatch.list"](
+ object(), "dispatch-list", {"limit": "invalid"}, "session"
+ )
+
+ assert channel.responses[-1]["ok"] is False
+ assert channel.responses[-1]["code"] == "A2A_OUTBOUND_STORE_INVALID"
+ assert channel.responses[-1]["error"] == "limit must be an integer"
+
+
+async def test_a2a_outbound_dispatch_list_clamps_limit_to_200():
+ channel = _WebChannelProbe()
+ registry = _OutboundRegistryProbe()
+ manager = A2AManager(
+ _ChannelManagerProbe(),
+ object(),
+ A2AIngressConfig(),
+ repository=_RepositoryProbe(),
+ channel_factory=lambda config, router: _ChannelProbe(),
+ outbound_registry=registry,
+ )
+ _register_web_handlers(WebHandlersBindParams(channel=channel, a2a_manager=manager))
+
+ await channel.methods["a2a.outbound.dispatch.list"](
+ object(), "dispatch-list", {"limit": 500}, "session"
+ )
+
+ assert channel.responses[-1]["payload"]["limit"] == 200
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"params", [{"agent_id": "agent-1"}, {"agent_id": "agent-1", "accept": "false"}]
@@ -342,6 +392,10 @@ def test_a2a_outbound_http_routes_map_to_rpc_methods():
assert routes[("POST", "/a2a/outbound/discover")] == "a2a.outbound.discover"
assert routes[("POST", "/a2a/outbound/agents")] == "a2a.outbound.register"
assert routes[("GET", "/a2a/outbound/agents")] == "a2a.outbound.list"
+ assert (
+ routes[("GET", "/a2a/outbound/dispatches")]
+ == "a2a.outbound.dispatch.list"
+ )
assert routes[("PATCH", "/a2a/outbound/agents/{agent_id}")] == "a2a.outbound.update"
assert (
routes[("POST", "/a2a/outbound/agents/{agent_id}:refresh")]
diff --git a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py
index e6438de788..8786e648b3 100644
--- a/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py
+++ b/tests/unit_tests/gateway/test_a2a_outbound_dispatcher.py
@@ -26,6 +26,7 @@ from jiuwenswarm.agents.harness.common.rails.a2a_outbound_toolkit_rail import (
)
from jiuwenswarm.agents.harness.common.tools.a2a_outbound_tools import (
A2AOutboundToolkit,
+ GatewayA2AOutboundToolBackend,
)
from jiuwenswarm.agents.harness.common.tools.acp_output_tools import (
get_acp_output_manager,
@@ -285,6 +286,7 @@ async def test_sync_dispatch_returns_normalized_final_message() -> None:
@pytest.mark.asyncio
async def test_real_http_stream_can_outlive_connect_timeout_within_sync_budget() -> None:
served = asyncio.Event()
+ received_requests = []
async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
try:
@@ -296,6 +298,7 @@ async def test_real_http_stream_can_outlive_connect_timeout_within_sync_budget()
content_length = int(line.split(":", 1)[1].strip())
break
request = json.loads((await reader.readexactly(content_length)).decode())
+ received_requests.append(request)
response = {
"jsonrpc": "2.0",
"id": request["id"],
@@ -369,6 +372,7 @@ async def test_real_http_stream_can_outlive_connect_timeout_within_sync_budget()
assert result["status"] == "completed"
assert result["result"]["text"] == "slow final"
+ assert received_requests[0]["params"]["configuration"]["returnImmediately"] is True
@pytest.mark.asyncio
@@ -405,9 +409,42 @@ async def test_sync_dispatch_polls_an_accepted_task_to_terminal() -> None:
assert result["status"] == "completed"
assert result["result"]["text"] == "polled answer"
+ assert client.sent_requests[0][0].configuration.return_immediately is True
assert len(client.get_requests) == 1
+async def test_sync_dispatch_gets_prompt_rejection_before_terminal_wait() -> None:
+ class _UnavailableExecutorClient(_FakeClient):
+ async def send_message(self, request, *, context=None):
+ self.sent_requests.append((request, context))
+ if request.configuration.return_immediately:
+ raise RuntimeError("executor unavailable")
+ await asyncio.Event().wait()
+ yield # pragma: no cover - keeps this an async generator
+
+ client = _UnavailableExecutorClient()
+ dispatcher, repository = await _dispatcher(client)
+ await repository.update_agent(
+ "agent-1",
+ lambda current: replace(current, sync_wait_seconds=1),
+ )
+
+ result = await asyncio.wait_for(
+ dispatcher.dispatch(
+ agent_id="agent-1",
+ task="do research",
+ mode="sync",
+ source_session_id="s1",
+ ),
+ timeout=0.2,
+ )
+
+ assert result["status"] == "dispatch_failed"
+ assert result["error_code"] == A2AOutboundErrorCode.DISPATCH_REJECTED.value
+ assert client.sent_requests[0][0].configuration.return_immediately is True
+
+
@pytest.mark.asyncio
async def test_async_dispatch_requires_remote_task_id_then_query_converges() -> None:
client = _FakeClient(
@@ -696,6 +733,67 @@ async def test_toolkit_missing_route_is_not_reported_as_remote_rejection() -> No
assert result["error_code"] == A2AOutboundErrorCode.MANAGER_UNAVAILABLE.value
[email protected]("method", [A2A_TOOL_DISPATCH_TASK, A2A_TOOL_GET_DISPATCH])
+async def test_gateway_backend_leaves_operation_timeout_to_manager(
+ monkeypatch, method
+) -> None:
+ output_manager = get_acp_output_manager()
+ calls = []
+
+ async def send(method, params, **kwargs):
+ calls.append((method, params, kwargs))
+ return {"result": {"ok": True}}
+
+ monkeypatch.setattr(output_manager, "send_jsonrpc_request", send)
+ monkeypatch.setattr(
+ GatewayA2AOutboundToolBackend,
+ "ready",
+ property(lambda _self: True),
+ )
+
+ result = await GatewayA2AOutboundToolBackend().call(
+ method,
+ {"agent_id": "agent-1", "task": "work", "mode": "sync"},
+ session_id="s1",
+ channel_id="web",
+ )
+
+ assert result == {"ok": True}
+ assert calls[0][2]["timeout"] is None
+ assert calls[0][2]["cancel_method"] == A2A_TOOL_CANCEL_CALL
+
+
+async def test_reverse_rpc_owner_loss_fails_request_without_transport_deadline(
+ monkeypatch,
+) -> None:
+ manager = get_acp_output_manager()
+ manager.reset_state()
+
+ async def delivered(_wire):
+ return True
+
+ monkeypatch.setattr(manager, "_send_push_callback", delivered)
+ request = asyncio.create_task(
+ manager.send_jsonrpc_request(
+ A2A_TOOL_GET_DISPATCH,
+ {"dispatch_id": "disp-1"},
+ session_id="s1",
+ timeout=None,
+ )
+ )
+ try:
+ while manager.pending_count == 0:
+ await asyncio.sleep(0)
+ manager.fail_pending_requests(RuntimeError("owner lost"))
+ with pytest.raises(RuntimeError, match="owner lost"):
+ await request
+ assert manager.pending_count == 0
+ finally:
+ manager.reset_state()
+
+
@pytest.mark.asyncio
async def test_gateway_bridge_binds_wire_session_instead_of_caller_params() -> None:
calls = []
diff --git a/tests/unit_tests/gateway/test_a2a_outbound_management.py b/tests/unit_tests/gateway/test_a2a_outbound_management.py
index 3f4fb02d97..397d9a86cf 100644
--- a/tests/unit_tests/gateway/test_a2a_outbound_management.py
+++ b/tests/unit_tests/gateway/test_a2a_outbound_management.py
@@ -14,6 +14,9 @@ from jiuwenswarm.gateway.a2a_manager.outbound import (
A2ADiscoveredAgent,
A2AOutboundCredentialStore,
A2AOutboundDiscoveryService,
+ A2AOutboundDispatch,
+ A2AOutboundDispatchMode,
+ A2AOutboundDispatchStatus,
A2AOutboundError,
A2AOutboundErrorCode,
A2AOutboundRegistry,
@@ -40,6 +43,58 @@ class _SecretProbe:
self.values.pop(key, None)
+async def test_dispatch_history_exposes_metadata_without_result_body() -> None:
+ registry, repository, _ = _registry()
+ await repository.create_dispatch(
+ A2AOutboundDispatch(
+ dispatch_id="disp-1",
+ agent_id="agent-1",
+ agent_revision=1,
+ mode=A2AOutboundDispatchMode.SYNC,
+ status=A2AOutboundDispatchStatus.COMPLETED,
+ request_message_id="msg-1",
+ source_session_id="session-1",
+ created_at="2026-08-27T01:00:00Z",
+ updated_at="2026-08-27T01:00:01Z",
+ finished_at="2026-08-27T01:00:01Z",
+ result={"text": "private response"},
+ )
+ )
+
+ history = await registry.list_dispatches(limit=200)
+
+ assert history["total"] == 1
+ assert history["items"][0]["dispatch_id"] == "disp-1"
+ assert history["items"][0]["updated_at"] == "2026-08-27T01:00:01Z"
+ assert "result" not in history["items"][0]
+
+
+async def test_dispatch_history_total_counts_records_beyond_page_limit() -> None:
+ registry, repository, _ = _registry()
+ for index in range(2):
+ stamp = f"2026-08-27T01:00:0{index}Z"
+ await repository.create_dispatch(
+ A2AOutboundDispatch(
+ dispatch_id=f"disp-{index}",
+ agent_id="agent-1",
+ agent_revision=1,
+ mode=A2AOutboundDispatchMode.ASYNC,
+ status=A2AOutboundDispatchStatus.TIMED_OUT,
+ request_message_id=f"msg-{index}",
+ source_session_id="session-1",
+ created_at=stamp,
+ updated_at=stamp,
+ )
+ )
+
+ history = await registry.list_dispatches(limit=1)
+
+ assert len(history["items"]) == 1
+ assert history["total"] == 2
+
+
class _FailingUpdateRepository(A2AOutboundRepository):
fail_next_update = False