Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(agent-team): support to expose the hitl events in the team leader's session (#1918)
DavdGao85f2df7a357d
diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsxindex 499bdc5e3..0a76b76b1 100644--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx@@ -20,6 +20,14 @@ interface ChatContentProps {) => void;autoComplete?: (input: string) => string | null;className?: string;+ /**+ * Optional content pinned at the bottom of the chat — between the+ * message scroll area and the text input (e.g. pending subagent HITL+ * cards on a team leader's view). Rendered below the conversation so+ * a pending confirmation sits next to the input, where the user is+ * looking, rather than scrolled off the top.+ */+ footerSlot?: React.ReactNode;/** @see TextInputProps.allowedInputTypes */allowedInputTypes: string[];/** @see TextInputProps.fileProcessor */@@ -34,6 +42,7 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({onUserConfirm,autoComplete,className,+ footerSlot,allowedInputTypes,fileProcessor,}) => {@@ -100,6 +109,7 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({)}</div></div>+ {footerSlot ? <div className="w-full max-w-full shrink-0">{footerSlot}</div> : null}<TextInputclassName="min-w-full max-w-full w-full"onSend={onSend}diff --git a/examples/web_ui/frontend/src/components/chat/SubagentHitlCard.tsx b/examples/web_ui/frontend/src/components/chat/SubagentHitlCard.tsxnew file mode 100644index 000000000..63224f7d2--- /dev/null+++ b/examples/web_ui/frontend/src/components/chat/SubagentHitlCard.tsx@@ -0,0 +1,56 @@+import type { ToolCallBlock } from '@agentscope-ai/agentscope/message';+import { Users } from 'lucide-react';++import { ConfirmCard } from './ConfirmCard';+import type { SubagentHitlEntry } from '@/hooks/useMessages';+import { useTranslation } from '@/i18n/useI18n';++/**+ * A pending HITL confirmation raised by a team *member* (worker)+ * session, surfaced on the *leader* view so the user can answer it+ * without drilling into the member's own session.+ *+ * Renders one {@link ConfirmCard} per pending tool call, reusing the+ * exact same confirm UI (and suggested-rules interaction) as a+ * first-party confirmation. The only addition is a header naming the+ * member that is asking.+ *+ * Confirmation is routed through {@link onConfirm}, which the parent+ * wires to ``useMessages``' ``onSubagentConfirm`` — POSTing the result+ * to the leader front door, where the backend forwards it to the+ * worker session (design §3.6).+ */+export function SubagentHitlCard({+ entry,+ onConfirm,+}: {+ entry: SubagentHitlEntry;+ onConfirm: (+ toolCall: ToolCallBlock,+ confirm: boolean,+ rules?: ToolCallBlock['suggested_rules'],+ ) => void;+}) {+ const { t } = useTranslation();+ const toolCalls = entry.event.tool_calls ?? [];++ if (toolCalls.length === 0) return null;++ return (+ <div className="ring ring-border rounded-xl w-full p-3 space-y-3 bg-secondary/30">+ <div className="flex items-center gap-2 text-sm font-medium text-secondary-foreground">+ <Users className="size-4 shrink-0" />+ <span>{t('chat.subagentConfirmTitle', { name: entry.worker_agent_name })}</span>+ </div>+ <div className="space-y-2">+ {toolCalls.map((toolCall) => (+ <ConfirmCard+ key={toolCall.id}+ toolCall={toolCall}+ onUserConfirm={(confirm, rules) => onConfirm(toolCall, confirm, rules)}+ />+ ))}+ </div>+ </div>+ );+}diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.tsindex 31727c20a..08d8822bd 100644--- a/examples/web_ui/frontend/src/hooks/useMessages.ts+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts@@ -17,6 +17,27 @@ import { sessionApi } from '@/api';import { chatApi } from '@/api';import { useAudioManager } from '@/context/AudioContext';+/**+ * One pending subagent HITL request, projected from a team *member*+ * session onto its *leader* session so the leader UI can render and+ * resolve it. Mirrors the Python payload written by+ * ``SubagentHitlProjector`` and pushed/replayed as a ``CustomEvent``+ * (``name="subagent_require_user_confirm"``).+ */+export type SubagentHitlEntry = {+ worker_session_id: string;+ worker_agent_id: string;+ worker_agent_name: string;+ reply_id: string;+ event_type: 'require_user_confirm' | 'require_external_execution';+ /** The original ``RequireUserConfirmEvent`` payload (serialized). */+ event: { tool_calls?: ToolCallBlock[] } & Record<string, unknown>;+ created_at: string;+};++const hitlKey = (e: { worker_session_id: string; reply_id: string }) =>+ `${e.worker_session_id}:${e.reply_id}`;+/*** Manages messages for a single ``(agentId, sessionId)`` pair.*@@ -68,6 +89,8 @@ export function useMessages(const [loading, setLoading] = useState(false);const [streaming, setStreaming] = useState(false);const [error, setError] = useState<Error | null>(null);+ // Pending subagent HITL cards projected onto this (leader) session.+ const [subagentHitl, setSubagentHitl] = useState<SubagentHitlEntry[]>([]);const msgsRef = useRef<Msg[]>([]);const currentReplyRef = useRef<Msg | null>(null);@@ -99,6 +122,19 @@ export function useMessages(optionsRef.current?.onTeamUpdated?.();} else if (custom.name === 'state_updated' && custom.value) {optionsRef.current?.onStateUpdated?.(custom.value as Record<string, unknown>);+ } else if (custom.name === 'subagent_require_user_confirm') {+ // A team member is asking for confirmation; show (or+ // refresh) its card on this leader view. Dedup by+ // (worker_session_id, reply_id).+ const e = custom.value as unknown as SubagentHitlEntry;+ setSubagentHitl((prev) => [+ ...prev.filter((x) => hitlKey(x) !== hitlKey(e)),+ e,+ ]);+ } else if (custom.name === 'subagent_user_confirm_result') {+ // The member resolved (or its run ended); clear the card.+ const v = custom.value as { worker_session_id: string; reply_id: string };+ setSubagentHitl((prev) => prev.filter((x) => hitlKey(x) !== hitlKey(v)));}return;}@@ -154,6 +190,7 @@ export function useMessages(setMsgs([]);setError(null);setStreaming(false);+ setSubagentHitl([]);audioManager?.disposeAll();if (!agentId || !sessionId) return;@@ -280,5 +317,68 @@ export function useMessages(abortRef.current?.abort();}, []);- return { msgs, loading, streaming, error, send, onUserConfirm, abort };+ /**+ * Confirm or deny a tool call that a *team member* is awaiting,+ * from this leader view (design §3.6 — backend routing).+ *+ * The result is POSTed to the **leader** session (the+ * ``(agentId, sessionId)`` this hook is bound to), NOT the worker.+ * The backend resolves ``reply_id`` → worker session via the+ * leader's pending hash and forwards the event to the worker's+ * continuation. The client never addresses the worker directly —+ * ``entry.worker_*`` ids are used only for local dedup / clearing.+ *+ * @param entry - The pending subagent HITL entry being resolved.+ * @param toolCall - The tool call block to confirm/deny.+ * @param confirm - Whether the user confirmed.+ * @param rules - Optional permission rules to attach.+ */+ const onSubagentConfirm = useCallback(+ async (+ entry: SubagentHitlEntry,+ toolCall: ToolCallBlock,+ confirm: boolean,+ rules?: ToolCallBlock['suggested_rules'],+ ) => {+ if (!agentId || !sessionId) return;++ const event: UserConfirmResultEvent = {+ type: EventType.USER_CONFIRM_RESULT,+ id: crypto.randomUUID(),+ created_at: new Date().toISOString(),+ reply_id: entry.reply_id, // worker's reply_id; backend maps it+ confirm_results: [+ { confirmed: confirm, tool_call: toolCall, rules: rules ?? null },+ ],+ };++ // Optimistically clear; the backend's clear event re-confirms.+ setSubagentHitl((prev) => prev.filter((x) => hitlKey(x) !== hitlKey(entry)));++ try {+ // Post to the leader front door — backend routes to the+ // worker session (§3.6). Do NOT address the worker here.+ await chatApi.trigger({+ agent_id: agentId,+ session_id: sessionId,+ input: event,+ });+ } catch (e) {+ setError(e as Error);+ }+ },+ [agentId, sessionId],+ );++ return {+ msgs,+ loading,+ streaming,+ error,+ send,+ onUserConfirm,+ onSubagentConfirm,+ subagentHitl,+ abort,+ };}diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex c5bfe0b7d..aaf23b990 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -96,6 +96,7 @@"placeholder": "Type a message...","send": "Send","confirmToolCall": "Allow this action?",+ "subagentConfirmTitle": "{{name}} requests confirmation","newSession": "New Session","noSessions": "No sessions yet","noMessages": "No Messages Yet",diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex 0096f8935..dcb3df2b0 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -96,6 +96,7 @@"placeholder": "输入消息...","send": "发送","confirmToolCall": "允许此操作?",+ "subagentConfirmTitle": "{{name}} 请求确认","newSession": "新会话","noSessions": "暂无会话","noMessages": "暂无消息",diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsxindex a076803a6..18c8c8f70 100644--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx@@ -5,6 +5,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';import type { ChatModelConfig, TTSModelConfig } from '@/api';import { sessionApi } from '@/api';import { ChatContent } from '@/components/chat/ChatContent.tsx';+import { SubagentHitlCard } from '@/components/chat/SubagentHitlCard';import { TaskPanel } from '@/components/chat/TaskPanel';import { CreateCredentialDialog } from '@/components/dialog/CreateCredentialDialog';import { WorkspaceDrawer } from '@/components/drawer/WorkspaceDrawer.tsx';@@ -90,10 +91,14 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewport// TODO: handle permission_context updates when permission UI is built}, []);- const { msgs, streaming, send, onUserConfirm } = useMessages(agentId, sessionId, {- onTeamUpdated: handleTeamUpdated,- onStateUpdated: handleStateUpdated,- });+ const { msgs, streaming, send, onUserConfirm, onSubagentConfirm, subagentHitl } = useMessages(+ agentId,+ sessionId,+ {+ onTeamUpdated: handleTeamUpdated,+ onStateUpdated: handleStateUpdated,+ },+ );const {mcps,loading: mcpsLoading,@@ -337,6 +342,26 @@ export function ChatViewport({ agentId, sessionId, onTeamUpdated }: ChatViewportdisabled={selectedModel === null}onSend={send}onUserConfirm={onUserConfirm}+ footerSlot={+ subagentHitl.length > 0 ? (+ <div className="space-y-2 pb-2">+ {subagentHitl.map((entry) => (+ <SubagentHitlCard+ key={`${entry.worker_session_id}:${entry.reply_id}`}+ entry={entry}+ onConfirm={(toolCall, confirm, rules) =>+ onSubagentConfirm(+ entry,+ toolCall,+ confirm,+ rules,+ )+ }+ />+ ))}+ </div>+ ) : null+ }allowedInputTypes={(selectedModelCard?.input_types ?? []).filter((t) =>/^(image|video|audio|text)\/.+/.test(t) ||diff --git a/src/agentscope/app/_manager/_wakeup_dispatcher.py b/src/agentscope/app/_manager/_wakeup_dispatcher.pyindex 6d9ef3953..7aa684235 100644--- a/src/agentscope/app/_manager/_wakeup_dispatcher.py+++ b/src/agentscope/app/_manager/_wakeup_dispatcher.py@@ -1,21 +1,38 @@# -*- coding: utf-8 -*--"""Single per-process dispatcher for cross-session wake-ups.+"""Single per-process dispatcher for all cross-session run triggers.-One asyncio task per process. Subscribes to the shared wake-up signal-channel and drains the durable wake-up queue on each signal. For each-queued entry whose session is idle, spawns a background-:meth:`ChatService.run` call through the shared-:class:`ChatRunRegistry`, so the spawned task can be looked up and-cancelled by :class:`CancelDispatcher`.+One asyncio task per process. Subscribes to the shared trigger signal+channel and drains the durable trigger queue on each signal. It is the+**sole** site that spawns :meth:`ChatService.run` into the shared+:class:`ChatRunRegistry`, which is what makes concurrent-spawn races+(two writers contending for one session's run slot → a spurious "already+has an active chat run" 409) structurally impossible: every run trigger+funnels through this one serial consumer.++Each queue entry carries a ``kind`` that selects how a busy session is+handled:++- ``wake`` (idle-session wake-up, ``input_msg=None``): skipped while the+ session is already running — the live run will drain the inbox.+- ``resume`` (a parked HITL run being fed its result): must *not* be+ skipped while running, because the session is typically still running+ the parked tail at trigger time. It is re-queued after a short backoff+ until the parked run releases its session lock, then spawned with the+ carried input event.All bus keys live on the :class:`MessageBus` base class (see-``enqueue_wakeup``, ``dequeue_wakeups``, ``subscribe_wakeup_signal``,-``session_is_running``), so this file has no hard-coded key strings.+``enqueue_wakeup`` / ``enqueue_input``, ``dequeue_wakeups``,+``subscribe_wakeup_signal``, ``session_is_running``), so this file has+no hard-coded key strings."""import asynciofrom typing import TYPE_CHECKING, Self+from pydantic import TypeAdapter+from ..._logging import logger+from ...event import UserConfirmResultEvent, ExternalExecutionResultEvent+from ..message_bus import MessageBusKeysif TYPE_CHECKING:from ..message_bus import MessageBus@@ -23,20 +40,33 @@ if TYPE_CHECKING:from .._service import ChatServicefrom ._chat_run_registry import ChatRunRegistry+# Parses a queued ``resume`` input dict back into its concrete event,+# discriminated by the ``type`` field shared by both result events.+_RESUME_INPUT_ADAPTER: TypeAdapter = TypeAdapter(+ UserConfirmResultEvent | ExternalExecutionResultEvent,+)++# Delay before re-queuing a ``resume`` trigger whose target session is+# still running (the parked run is finishing and about to free its+# lock). Short enough to feel instant to the user, long enough to avoid+# a hot re-enqueue loop while the lock is held.+_RESUME_RETRY_BACKOFF_SECS = 0.1+class WakeupDispatcher:- """One asyncio task per process, draining the shared wake-up queue.+ """One asyncio task per process, draining the shared trigger queue.Args:message_bus (`MessageBus`):Application message bus. Used for signal subscription,- queue drain, and ``session_is_running`` checks.+ queue drain, ``session_is_running`` checks, and re-queuing+ deferred ``resume`` triggers.storage (`StorageBase`):Persistent storage backend. Consulted before spawning a- run so wake-ups whose target session has been deleted are+ run so triggers whose target session has been deleted aredropped instead of crashing :class:`ChatService.run`.chat_service (`ChatService`):- Drives the actual chat run when waking an idle session.+ Drives the actual chat run when a trigger fires.chat_run_registry (`ChatRunRegistry`):Per-process registry that holds the spawned task handle soit can be located by :class:`CancelDispatcher`.@@ -57,7 +87,7 @@ class WakeupDispatcher:storage (`StorageBase`):Persistent storage backend.chat_service (`ChatService`):- Drives idle-session wake-ups via :meth:`ChatService.run`.+ Drives session runs via :meth:`ChatService.run`.chat_run_registry (`ChatRunRegistry`):Shared chat-run registry to spawn into."""@@ -66,13 +96,17 @@ class WakeupDispatcher:self._chat_service = chat_serviceself._registry = chat_run_registryself._task: asyncio.Task | None = None+ # Detached backoff timers for deferred ``resume`` re-enqueues.+ # Held so they are not garbage-collected mid-sleep and can be+ # cancelled on shutdown.+ self._retry_tasks: set[asyncio.Task] = set()async def __aenter__(self) -> Self:"""Start the dispatcher loop and wait until its bussubscription is live.Also performs an initial drain right after subscription so- wake-ups produced while this process was down (durable in+ triggers produced while this process was down (durable inthe queue) are picked up immediately on startup.Returns:@@ -88,7 +122,16 @@ class WakeupDispatcher:return selfasync def __aexit__(self, *exc: object) -> None:- """Cancel the dispatcher loop on context exit."""+ """Cancel the dispatcher loop and any pending retries."""+ retries = list(self._retry_tasks)+ for retry in retries:+ retry.cancel()+ for retry in retries:+ try:+ await retry+ except asyncio.CancelledError:+ pass+ self._retry_tasks.clear()if self._task is None:returnself._task.cancel()@@ -110,7 +153,7 @@ class WakeupDispatcher:ready (`asyncio.Event`):Signalled after the underlying SUBSCRIBE completes.:meth:`start` blocks on this so callers can publish a- wake-up immediately after start without racing.+ trigger immediately after start without racing."""try:async for _signal in self._bus.subscribe_wakeup_signal(@@ -123,7 +166,7 @@ class WakeupDispatcher:)async def _drain_and_dispatch(self) -> None:- """Read up to a batch of wake-up entries and dispatch them."""+ """Read up to a batch of trigger entries and dispatch each."""try:entries = await self._bus.dequeue_wakeups(max_count=64)except Exception: # pylint: disable=broad-except@@ -137,55 +180,178 @@ class WakeupDispatcher:agent_id = payload["agent_id"]except (KeyError, TypeError):logger.warning(- "WakeupDispatcher: skipping malformed wake-up entry %r",+ "WakeupDispatcher: skipping malformed trigger entry %r",payload,)continue+ # Entries from older producers omit ``kind`` — treat as wake.+ kind = payload.get("kind", MessageBusKeys.WAKEUP_KIND_WAKE)+ await self._dispatch_one(+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ kind=kind,+ raw_input=payload.get("input"),+ )- if await self._bus.session_is_running(session_id):- continue+ async def _dispatch_one(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ kind: str,+ raw_input: dict | None,+ ) -> None:+ """Dispatch a single trigger entry by its ``kind``.- # Orphan guard: the wake-up queue is unaware of session- # lifecycle. A wake-up enqueued before the session was- # deleted (e.g. by a BG task completion callback or a- # schedule trigger) will still arrive here. Drop it- # rather than letting ChatService.run crash on a missing- # storage record.- if (- await self._storage.get_session(+ Args:+ user_id (`str`):+ The owning user id.+ session_id (`str`):+ The session to trigger.+ agent_id (`str`):+ The agent that owns the session.+ kind (`str`):+ Trigger kind (``wake`` / ``resume``); see module docstring.+ raw_input (`dict | None`):+ Serialised input event for ``resume`` triggers, else+ ``None``.+ """+ is_resume = kind == MessageBusKeys.WAKEUP_KIND_RESUME++ if await self._bus.session_is_running(session_id):+ if is_resume:+ # The session is busy finishing its parked tail. Do NOT+ # drop the resume — re-queue it after a short backoff so+ # it lands once the parked run releases its lock.+ self._schedule_resume_retry(user_id,- agent_id,session_id,+ agent_id,+ raw_input,)- is None- ):+ # ``wake`` triggers are safe to drop while running — the+ # live run drains the inbox itself.+ return++ # Orphan guard: the queue is unaware of session lifecycle. A+ # trigger enqueued before the session was deleted (e.g. by a+ # BG-task completion callback or a schedule trigger) will still+ # arrive here. Drop it rather than letting ChatService.run crash+ # on a missing storage record.+ if (+ await self._storage.get_session(user_id, agent_id, session_id)+ is None+ ):+ logger.warning(+ "WakeupDispatcher: dropping %s trigger for session %s "+ "(agent %s, user %s) — session no longer exists in "+ "storage; it was likely enqueued before the session was "+ "deleted.",+ kind,+ session_id,+ agent_id,+ user_id,+ )+ return++ input_msg: UserConfirmResultEvent | ExternalExecutionResultEvent | None+ input_msg = None+ if is_resume:+ if raw_input is None:logger.warning(- "WakeupDispatcher: dropping wake-up for session %s "- "(agent %s, user %s) — session no longer exists in "- "storage; the wake-up was likely enqueued before "- "the session was deleted.",+ "WakeupDispatcher: dropping resume trigger for session "+ "%s — no input event carried.",session_id,- agent_id,+ )+ return+ try:+ input_msg = _RESUME_INPUT_ADAPTER.validate_python(raw_input)+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: dropping resume trigger for session "+ "%s — input event failed to parse: %r",+ session_id,+ raw_input,+ )+ return++ try:+ self._registry.spawn(+ self._chat_service.run(+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ input_msg=input_msg,+ ),+ session_id=session_id,+ name=f"{kind}-run:{session_id}",+ )+ except RuntimeError:+ # A local run was registered between the running-check and+ # the spawn. For ``wake`` that run will drain the inbox; for+ # ``resume`` re-queue so the result is not lost.+ if is_resume:+ self._schedule_resume_retry(user_id,+ session_id,+ agent_id,+ raw_input,)- continue+ else:+ logger.debug(+ "WakeupDispatcher: skipping wake trigger for session "+ "%s; a local run is already registered.",+ session_id,+ )++ def _schedule_resume_retry(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ raw_input: dict | None,+ ) -> None:+ """Re-enqueue a ``resume`` trigger after a short backoff.++ Spawns a detached timer that sleeps, then re-enqueues the resume+ (which re-fires the signal, re-driving the drain). This keeps the+ resume alive across the window where the parked run still holds+ the session lock, without a hot re-enqueue loop.+ Args:+ user_id (`str`):+ The owning user id.+ session_id (`str`):+ The session to resume.+ agent_id (`str`):+ The agent that owns the session.+ raw_input (`dict | None`):+ The serialised input event to redeliver.+ """++ async def _retry() -> None:try:- self._registry.spawn(- self._chat_service.run(- user_id=user_id,- session_id=session_id,- agent_id=agent_id,- input_msg=None,- ),+ await asyncio.sleep(_RESUME_RETRY_BACKOFF_SECS)+ await self._bus.enqueue_input(+ user_id=user_id,session_id=session_id,- name=f"wakeup-run:{session_id}",+ agent_id=agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_RESUME,+ inputs=raw_input,)- except RuntimeError:- # Another spawn won the race for this session in this- # process; the existing run will drain the inbox.- logger.debug(- "WakeupDispatcher: skipping wake-up for session %s; "- "a local run is already registered.",+ except asyncio.CancelledError:+ pass+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: failed to re-enqueue resume trigger "+ "for session %s.",session_id,)++ task = asyncio.create_task(+ _retry(),+ name=f"resume-retry:{session_id}",+ )+ self._retry_tasks.add(task)+ task.add_done_callback(self._retry_tasks.discard)diff --git a/src/agentscope/app/_router/_chat.py b/src/agentscope/app/_router/_chat.pyindex f66b585ea..63898494d 100644--- a/src/agentscope/app/_router/_chat.py+++ b/src/agentscope/app/_router/_chat.py@@ -6,6 +6,19 @@ chat run as a background task and returns immediately. Events producedby the run are published to the message bus and delivered to thefrontend via the long-lived ``GET /sessions/{sid}/stream`` SSEconnection provided by the session router.++Two trigger paths, deliberately asymmetric:++- **New user message(s)** are spawned directly into the+ :class:`ChatRunRegistry`. The registry's single-run-per-session rule+ surfaces as a 409, which is exactly the desired double-submit guard.+- **HITL results** (``UserConfirmResultEvent`` /+ ``ExternalExecutionResultEvent``) are *enqueued* onto the shared+ run-trigger queue and drained by the single+ :class:`WakeupDispatcher`. Routing the resume through the queue keeps+ the dispatcher the sole spawn site, so a resume can never collide with+ the worker's still-finishing parked run (the old 409 race) — the+ dispatcher serialises them."""from fastapi import APIRouter, Depends, HTTPException, status@@ -13,10 +26,13 @@ from ..deps import (get_chat_run_registry,get_chat_service,get_current_user_id,+ get_message_bus,)from ._schema import ChatRequest, ChatTriggerResponsefrom .._manager import ChatRunRegistry-from .._service import ChatService+from .._service import ChatService, SessionProjection, SubagentHitlProjector+from ..message_bus import MessageBus, MessageBusKeys+from ...event import UserConfirmResultEvent, ExternalExecutionResultEventchat_router = APIRouter(prefix="/chat",@@ -35,21 +51,22 @@ async def chat(user_id: str = Depends(get_current_user_id),chat_service: ChatService = Depends(get_chat_service),chat_run_registry: ChatRunRegistry = Depends(get_chat_run_registry),+ message_bus: MessageBus = Depends(get_message_bus),) -> ChatTriggerResponse:"""Trigger a chat run for the specified session.- The run executes as a background task tracked by- :class:`ChatRunRegistry`. Events produced during the run are- published to the message bus and delivered to any active- ``GET /sessions/{session_id}/stream`` SSE subscriber. The caller- does **not** receive events from this endpoint's response body.+ Events produced during the run are published to the message bus and+ delivered to any active ``GET /sessions/{session_id}/stream`` SSE+ subscriber. The caller does **not** receive events from this+ endpoint's response body.Accepts the same ``input`` payloads as before:- - ``Msg`` / ``list[Msg]``: new user message(s).+ - ``Msg`` / ``list[Msg]``: new user message(s) — spawned directly.- ``UserConfirmResultEvent`` / ``ExternalExecutionResultEvent``:- resume a paused tool call (human-in-the-loop).- - ``None``: continue from current state.+ resume a paused tool call (human-in-the-loop) — routed to the+ owning session and enqueued for the dispatcher.+ - ``None``: continue from current state — spawned directly.Args:request (`ChatRequest`):@@ -60,16 +77,62 @@ async def chat(Injected application-wide chat service.chat_run_registry (`ChatRunRegistry`):Injected per-process chat-run registry.+ message_bus (`MessageBus`):+ Injected message bus, used to resolve subagent-confirm+ routing and to enqueue resume triggers.Returns:`ChatTriggerResponse`:- Confirms the run was scheduled.+ Confirms the run was scheduled (for a resume, that it was+ enqueued).Raises:`HTTPException`:409 if a chat run for this session is already in flight inthis process (the registry enforces single-run-per-session).+ Only direct-spawn paths (new messages / ``None``) can raise+ this; the enqueued resume path never does."""+ # ------------------------------------------------------------------+ # HITL resume — route to the owning session, then enqueue.+ #+ # A confirmation / external-result POSTed to a *leader* session may+ # actually belong to a team *member*: the leader is the single front+ # door clients talk to. Resolve the owning worker HERE, then enqueue+ # a ``resume`` trigger for that session. The single WakeupDispatcher+ # drains it — spawning under the *worker* session id, serialised+ # behind any still-finishing parked run, so there is no registry+ # collision (no 409) and the leader's run slot is never occupied by+ # the worker's resume.+ # ------------------------------------------------------------------+ if isinstance(+ request.input,+ (UserConfirmResultEvent, ExternalExecutionResultEvent),+ ):+ run_session_id = request.session_id+ run_agent_id = request.agent_id+ target = await SubagentHitlProjector.resolve(+ SessionProjection(message_bus),+ request.session_id,+ request.input.reply_id,+ )+ if target is not None:+ run_session_id = target["worker_session_id"]+ run_agent_id = target["worker_agent_id"]++ await message_bus.enqueue_input(+ user_id=user_id,+ session_id=run_session_id,+ agent_id=run_agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_RESUME,+ inputs=request.input.model_dump(mode="json"),+ )+ return ChatTriggerResponse(status="started", session_id=run_session_id)++ # ------------------------------------------------------------------+ # New user message(s) / None — spawn directly. The registry's+ # single-run-per-session rule is the desired double-submit guard.+ # ------------------------------------------------------------------try:chat_run_registry.spawn(chat_service.run(diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex 3b72d790d..e7b648311 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -25,7 +25,7 @@ from ._schema import (UpdateSessionRequest,)from ..message_bus import MessageBus-from .._service import SessionService+from .._service import SessionService, SessionProjection, SubagentHitlProjectorfrom ..storage import (AgentRecord,ChatModelConfig,@@ -35,6 +35,8 @@ from ..storage import (StorageBase,TeamRecord,)+from ...message import ToolCallState+from ...event import CustomEventasync def _build_team_detail(@@ -422,6 +424,61 @@ _HEARTBEAT_INTERVAL_SECS = 30# Interval between SSE heartbeat comment frames (``:\\n\\n``).+async def _worker_still_asking(+ storage: StorageBase,+ user_id: str,+ worker_agent_id: str,+ worker_session_id: str,+ reply_id: str,+) -> bool:+ """Return whether a worker session is still parked on the ASKING+ tool call identified by ``reply_id``.++ This is the reconcile-on-read check (design §3.5): the worker+ session's own ``state.context`` is the single source of truth for+ "does this confirmation still need answering". A leader-side+ pending projection whose worker has already resolved / cancelled+ the call is a ghost and must not be replayed.++ Mirrors the wakeup guard in+ :meth:`ChatService._run_impl` — a request is "still asking" when+ the tail ``AssistantMsg`` of the worker carries a tool call in+ ``ASKING`` or ``SUBMITTED`` state for the matching ``reply_id``.++ Args:+ storage (`StorageBase`):+ Application storage.+ user_id (`str`):+ The owner user id.+ worker_agent_id (`str`):+ The worker agent that owns the session.+ worker_session_id (`str`):+ The worker session to inspect.+ reply_id (`str`):+ The reply id the pending request belongs to.++ Returns:+ `bool`:+ ``True`` if the worker is still awaiting confirmation for+ ``reply_id``; ``False`` otherwise (resolved, cancelled, or+ the session/record is gone).+ """+ session = await storage.get_session(+ user_id,+ worker_agent_id,+ worker_session_id,+ )+ if session is None or not session.state.context:+ return False+ last_msg = session.state.context[-1]+ if last_msg.role != "assistant" or last_msg.id != reply_id:+ return False+ return any(+ tc.state in (ToolCallState.ASKING, ToolCallState.SUBMITTED)+ for tc in last_msg.get_content_blocks("tool_call")+ )++@session_router.get("/{session_id}/stream",summary="Subscribe to a session's event stream (SSE)",@@ -477,6 +534,42 @@ async def stream_session_events():yield f"data: {json.dumps(event)}\n\n"+ # 1b. Inject pending subagent HITL cards projected onto this+ # session as a team leader (design §3.5). These live in a+ # durable Redis hash — NOT in the replay log (trimmed per+ # run) nor in the leader's own Msg history — so a fresh+ # reconnect after the worker parked still surfaces them.+ #+ # Reconcile-on-read: the worker session's own context is the+ # SSOT. Inject only when the worker is still ASKING; drop and+ # delete ghosts (worker resolved/cancelled without clearing).+ projection = SessionProjection(message_bus)+ for payload in await projection.list(+ session_id,+ SubagentHitlProjector.KIND,+ ):+ if not await _worker_still_asking(+ storage,+ user_id,+ payload["worker_agent_id"],+ payload["worker_session_id"],+ payload["reply_id"],+ ):+ await projection.delete(+ session_id,+ SubagentHitlProjector.KIND,+ SubagentHitlProjector.entry_id(+ payload["worker_session_id"],+ payload["reply_id"],+ ),+ )+ continue+ custom = CustomEvent(+ name=SubagentHitlProjector.EVT_REQUIRE,+ value=payload,+ )+ yield f"data: {json.dumps(custom.model_dump(mode='json'))}\n\n"+# 2. Live subscribe via a background feeder task that pushes# events into a queue. The main loop reads from the queue# with a timeout so we can interleave heartbeat frames.diff --git a/src/agentscope/app/_service/__init__.py b/src/agentscope/app/_service/__init__.pyindex 1b22f7b06..6b15f0cad 100644--- a/src/agentscope/app/_service/__init__.py+++ b/src/agentscope/app/_service/__init__.py@@ -5,11 +5,15 @@ from ._embedding import get_embedding_modelfrom ._model import get_modelfrom ._tts_model import get_tts_modelfrom ._session import SessionService+from ._session_projection import SessionProjection+from ._projectors import SubagentHitlProjectorfrom ._toolkit import get_toolkit__all__ = ["ChatService","SessionService",+ "SessionProjection",+ "SubagentHitlProjector","get_embedding_model","get_model","get_tts_model",diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex de5a2023a..0bc1230b5 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -14,7 +14,7 @@ that wants them subscribes through thefrom fastapi import HTTPExceptionfrom ..message_bus import MessageBus-from ..storage import StorageBase+from ..storage import StorageBase, AgentRecord, SessionRecordfrom .._manager import BackgroundTaskManager, SchedulerManagerfrom ..workspace_manager import WorkspaceManagerBasefrom ..middleware import (@@ -26,15 +26,19 @@ from ...middleware import TTSMiddlewarefrom .._types import (AgentMiddlewareFactory,AgentToolFactory,+ EventProjector,SubAgentTemplate,)from ._model import get_modelfrom ._tts_model import get_tts_modelfrom ._toolkit import get_toolkit+from ._session_projection import SessionProjection+from ._projectors import SubagentHitlProjectorfrom ..._logging import loggerfrom ...agent import Agent, ModelConfigfrom ...event import (+ AgentEvent,ReplyStartEvent,UserConfirmResultEvent,ExternalExecutionResultEvent,@@ -69,6 +73,7 @@ class ChatService:extra_agent_tools: AgentToolFactory | None = None,custom_subagent_templates: dict[str, SubAgentTemplate] | None = None,custom_agent_cls: type[Agent] | None = None,+ extra_projectors: list[EventProjector] | None = None,) -> None:"""Initialize chat service.@@ -107,6 +112,12 @@ class ChatService:custom_agent_cls (`type[Agent] | None`, optional):Custom :class:`Agent` subclass for assembling agents.Falls back to :class:`Agent` when ``None``.+ extra_projectors (`list[EventProjector] | None`, optional):+ Additional cross-session event projectors to run after+ the built-in ones (mirrors the ``extra_agent_*``+ injection style). Each is invoked once per produced+ event to mirror a UI feed onto another session; see+ :class:`~agentscope.app._types.EventProjector`."""self._storage = storageself._workspace_manager = workspace_manager@@ -117,6 +128,11 @@ class ChatService:self._extra_agent_tools = extra_agent_toolsself._sub_agent_templates = custom_subagent_templatesself._agent_cls = custom_agent_cls or Agent+ self._projection = SessionProjection(message_bus)+ self._projectors: list[EventProjector] = [+ SubagentHitlProjector(storage),+ *(extra_projectors or []),+ ]async def run(self,@@ -389,6 +405,12 @@ class ChatService:session_id,event.model_dump(mode="json"),)+ await self._project_event(+ user_id,+ session_record,+ agent_record,+ event,+ )if isinstance(event, ReplyStartEvent):reply_msg = AssistantMsg(id=event.reply_id,@@ -422,6 +444,12 @@ class ChatService:session_id,event.model_dump(mode="json"),)+ await self._project_event(+ user_id,+ session_record,+ agent_record,+ event,+ )if reply_msg is not None:reply_msg.append_event(event)@@ -447,3 +475,48 @@ class ChatService:# ``session_run.__aexit__`` trims the replay log before# releasing the lock — see :meth:`MessageBus.session_run`.++ async def _project_event(+ self,+ user_id: str,+ session_record: SessionRecord,+ agent_record: AgentRecord,+ event: AgentEvent,+ ) -> None:+ """Run every registered projector against one produced event.++ Each :class:`~agentscope.app._types.EventProjector` decides+ whether the event is relevant to its cross-session UI feed and,+ if so, mirrors it onto the owning session via the shared+ :class:`SessionProjection`. Projectors are independent: one+ failing must neither tear down the producing run nor block the+ others, so each call is guarded individually and its error+ logged. Adding a feed means adding a projector — no change here.++ Args:+ user_id (`str`):+ The owner user id.+ session_record (`SessionRecord`):+ The currently-running session's record.+ agent_record (`AgentRecord`):+ The currently-running agent's record.+ event (`AgentEvent`):+ The event just published to this session's channel.+ """+ for projector in self._projectors:+ try:+ await projector.maybe_project(+ user_id,+ session_record,+ agent_record,+ event,+ self._projection,+ )+ except Exception as e: # pylint: disable=broad-except+ logger.warning(+ "Projector %s failed on event %s from session %s: %s",+ type(projector).__name__,+ type(event).__name__,+ session_record.id,+ str(e),+ )diff --git a/src/agentscope/app/_service/_projectors/__init__.py b/src/agentscope/app/_service/_projectors/__init__.pynew file mode 100644index 000000000..7a3ae5117--- /dev/null+++ b/src/agentscope/app/_service/_projectors/__init__.py@@ -0,0 +1,13 @@+# -*- coding: utf-8 -*-+"""Built-in event projectors.++Each projector mirrors one cross-session UI feed onto the owning+session via the shared+:class:`~agentscope.app._service._session_projection.SessionProjection`+primitive. See :class:`~agentscope.app._types.EventProjector`.+"""+from ._subagent_hitl import SubagentHitlProjector++__all__ = [+ "SubagentHitlProjector",+]diff --git a/src/agentscope/app/_service/_projectors/_subagent_hitl.py b/src/agentscope/app/_service/_projectors/_subagent_hitl.pynew file mode 100644index 000000000..cc5e03b86--- /dev/null+++ b/src/agentscope/app/_service/_projectors/_subagent_hitl.py@@ -0,0 +1,270 @@+# -*- coding: utf-8 -*-+"""Projector that bridges team-member HITL events to leader sessions.++When a team *member* (worker) session hits a tool call that needs human+confirmation, the worker run parks on an ``ASKING`` tool call in its+**own** session — invisible to a client subscribed only to the *leader*+session's event stream. This projector mirrors each such pending+request onto the leader session so the leader UI can render and resolve+it, and clears it when the request is answered.++It is a thin strategy over the generic+:class:`~agentscope.app._service._session_projection.SessionProjection`+primitive: this file holds only the HITL-specific policy (which events+matter, how to resolve the leader, what the card payload looks like).+The durable hash, live notification, and key conventions all live in+the shared primitive.++Persistence model (see the design doc, §2.4):++- **Authoritative state** is the worker session's own ``state.context``+ (the ``ASKING`` tool call). The projection is only a mirror.+- The projected hash entry carries **no TTL**: a legitimate+ confirmation can stay pending indefinitely. Stale entries (worker+ cancelled/crashed without clearing) are healed by reconcile-on-read+ at SSE replay time.+"""+from datetime import datetime+from typing import TYPE_CHECKING++from ....event import (+ RequireUserConfirmEvent,+ RequireExternalExecutionEvent,+ UserConfirmResultEvent,+ ExternalExecutionResultEvent,+ ReplyEndEvent,+)++if TYPE_CHECKING:+ from ...storage import AgentRecord, SessionRecord, StorageBase+ from ....event import AgentEvent+ from .._session_projection import SessionProjection+++class SubagentHitlProjector:+ """Project pending team-member HITL requests onto leader sessions.++ Holds the storage handle it needs to resolve a worker's team (and+ thus its leader). The :class:`SessionProjection` it writes through+ is passed in per call by+ :class:`~agentscope.app._service.ChatService`, which also resolves+ confirm-routing and SSE replay through this projector's+ :meth:`resolve` / :meth:`entry_id` helpers.+ """++ KIND = "subagent_hitl"+ """Projection feed key (namespaces the entry within a session's+ shared projection hash)."""++ EVT_REQUIRE = "subagent_require_user_confirm"+ """``CustomEvent.name`` used to push/replay a pending request to the+ leader's event stream."""++ EVT_RESULT = "subagent_user_confirm_result"+ """``CustomEvent.name`` used to tell the leader UI a pending request+ has been resolved and its card should be cleared."""++ def __init__(self, storage: "StorageBase") -> None:+ """Bind the storage backend.++ Args:+ storage (`StorageBase`):+ Application storage, used to resolve the team (and hence+ the leader session) a worker session belongs to.+ """+ self._storage = storage++ @staticmethod+ def entry_id(worker_session_id: str, reply_id: str) -> str:+ """Return the projection entry id for one pending request.++ Args:+ worker_session_id (`str`):+ The worker session that emitted the HITL request.+ reply_id (`str`):+ The worker-side reply id the request belongs to.++ Returns:+ `str`:+ The entry id, ``"{worker_session_id}:{reply_id}"``.+ """+ return f"{worker_session_id}:{reply_id}"++ async def maybe_project(+ self,+ user_id: str,+ session_record: "SessionRecord",+ agent_record: "AgentRecord",+ event: "AgentEvent",+ projection: "SessionProjection",+ ) -> None:+ """Mirror a worker HITL event onto its team's leader session.++ When a *worker* session emits an HITL request, write the pending+ card (durable entry + live notification) onto the leader; when+ it resolves one or its reply ends, clear the card. No-op for+ non-team sessions and for the leader session itself (a leader's+ own HITL reaches its client directly).++ Args:+ user_id (`str`):+ The owner of the running session.+ session_record (`SessionRecord`):+ The currently-running session's record.+ agent_record (`AgentRecord`):+ The currently-running agent's record. Only+ ``source == "team"`` agents forward.+ event (`AgentEvent`):+ The event just published to this session's channel.+ projection (`SessionProjection`):+ Shared primitive used to write the durable entry and the+ live notification.+ """+ # Fast path: only team-member sessions forward anything, and+ # only for the event kinds we care about.+ if agent_record.source != "team" or not session_record.team_id:+ return+ if not isinstance(+ event,+ (+ RequireUserConfirmEvent,+ RequireExternalExecutionEvent,+ UserConfirmResultEvent,+ ExternalExecutionResultEvent,+ ReplyEndEvent,+ ),+ ):+ return++ team = await self._storage.get_team(+ user_id,+ session_record.team_id,+ )+ if team is None or team.session_id == session_record.id:+ # No team, or this IS the leader session — nothing to mirror.+ return+ leader_sid = team.session_id++ if isinstance(+ event,+ (RequireUserConfirmEvent, RequireExternalExecutionEvent),+ ):+ payload = {+ "worker_session_id": session_record.id,+ "worker_agent_id": agent_record.id,+ "worker_agent_name": agent_record.data.name,+ "reply_id": event.reply_id,+ "event_type": (+ "require_user_confirm"+ if isinstance(event, RequireUserConfirmEvent)+ else "require_external_execution"+ ),+ "event": event.model_dump(mode="json"),+ "created_at": datetime.now().isoformat(),+ }+ await projection.upsert(+ leader_sid,+ self.KIND,+ self.entry_id(session_record.id, event.reply_id),+ payload,+ )+ await projection.publish(leader_sid, self.EVT_REQUIRE, payload)+ else:+ # Clear the pending card. ``ReplyEndEvent`` is the primary+ # clear signal (the resume's continuation event is NOT+ # republished through the stream); the explicit result+ # events clear early when they do flow through. All are+ # idempotent — deleting an already-gone entry is a no-op.+ await projection.delete(+ leader_sid,+ self.KIND,+ self.entry_id(session_record.id, event.reply_id),+ )+ await projection.publish(+ leader_sid,+ self.EVT_RESULT,+ {+ "worker_session_id": session_record.id,+ "reply_id": event.reply_id,+ },+ )++ @classmethod+ async def resolve(+ cls,+ projection: "SessionProjection",+ leader_sid: str,+ reply_id: str,+ ) -> dict | None:+ """Find the pending entry for ``reply_id`` under a leader.++ Used by the confirm-routing entry point (the chat router): given+ a confirm result POSTed to the leader session, locate which+ worker session it actually belongs to so the result can be+ forwarded there.++ Args:+ projection (`SessionProjection`):+ The shared projection store to scan.+ leader_sid (`str`):+ The leader session the confirm result was POSTed to.+ reply_id (`str`):+ The worker-side reply id carried by the confirm result.++ Returns:+ `dict | None`:+ The stored payload (with ``worker_session_id`` /+ ``worker_agent_id``), or ``None`` when no pending entry+ matches — meaning the confirm is the leader's own.+ """+ for entry in await projection.list(leader_sid, cls.KIND):+ if entry.get("reply_id") == reply_id:+ return entry+ return None++ @classmethod+ async def purge(+ cls,+ projection: "SessionProjection",+ leader_sid: str,+ ) -> None:+ """Drop every pending HITL entry for a leader session.++ Used when the leader session (or its team) is deleted. Scoped to+ this feed so other projections on the same session survive.++ Args:+ projection (`SessionProjection`):+ The shared projection store.+ leader_sid (`str`):+ The leader session to purge.+ """+ await projection.purge(leader_sid, cls.KIND)++ @classmethod+ async def drop_worker(+ cls,+ projection: "SessionProjection",+ leader_sid: str,+ worker_sid: str,+ ) -> None:+ """Drop every pending entry that originated from one worker.++ Used when a single worker session is deleted while the leader+ survives.++ Args:+ projection (`SessionProjection`):+ The shared projection store.+ leader_sid (`str`):+ The leader session the entries are projected onto.+ worker_sid (`str`):+ The worker session whose entries should be dropped.+ """+ for entry in await projection.list(leader_sid, cls.KIND):+ if entry.get("worker_session_id") == worker_sid:+ await projection.delete(+ leader_sid,+ cls.KIND,+ cls.entry_id(worker_sid, entry["reply_id"]),+ )diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.pyindex b344c0f4e..e6a975aa9 100644--- a/src/agentscope/app/_service/_session.py+++ b/src/agentscope/app/_service/_session.py@@ -49,6 +49,8 @@ import asynciofrom ..message_bus import MessageBusfrom ..storage import StorageBase+from ._session_projection import SessionProjection+from ._projectors import SubagentHitlProjectorfrom ..._logging import logger@@ -88,6 +90,7 @@ class SessionService:"""self._storage = storageself._bus = message_bus+ self._projection = SessionProjection(message_bus)# ------------------------------------------------------------------# Cancel@@ -206,6 +209,10 @@ class SessionService:)all_sids = [session_id, *worker_sids]+ # Clean leader-side subagent HITL projections before storage+ # cascades remove the records we need to resolve roles from.+ await self._purge_subagent_hitl(user_id, agent_id, session_id)+await self._cancel_runs(all_sids)deleted = await self._storage.delete_session(user_id,@@ -381,3 +388,69 @@ class SessionService:await asyncio.gather(*(self._bus.session_purge(sid) for sid in session_ids),)++ async def _purge_subagent_hitl(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ ) -> None:+ """Clean leader-side subagent HITL projections for a session+ about to be deleted (design §3.7).++ Two cases, resolved from the session's role:++ - **Leader session** (it leads a team): purge the entire hash+ keyed by this session — every projected member card goes.+ - **Worker session** (it has a ``team_id`` but is not the+ leader): drop just this worker's entries from the *leader's*+ hash, leaving sibling members' cards intact.++ Must run before storage cascades remove the team / session+ records this resolution depends on. Failures are swallowed — a+ stale projection is self-healed by reconcile-on-read and must+ not block the delete cascade.++ Args:+ user_id (`str`):+ The owner user id.+ agent_id (`str`):+ The agent that owns ``session_id``.+ session_id (`str`):+ The session being deleted.+ """+ try:+ session = await self._storage.get_session(+ user_id,+ agent_id,+ session_id,+ )+ if session is None or not session.team_id:+ # Not in a team — also clear any hash that may have been+ # created with this session as a (future) leader key.+ await SubagentHitlProjector.purge(self._projection, session_id)+ return++ team = await self._storage.get_team(user_id, session.team_id)+ if team is None:+ await SubagentHitlProjector.purge(self._projection, session_id)+ return++ if team.session_id == session_id:+ # Leader session — drop the whole projection store.+ await SubagentHitlProjector.purge(self._projection, session_id)+ else:+ # Worker session — drop only its entries from the+ # leader's store.+ await SubagentHitlProjector.drop_worker(+ self._projection,+ team.session_id,+ session_id,+ )+ except Exception as e: # pylint: disable=broad-except+ logger.warning(+ "Failed to purge subagent HITL projection for session "+ "%s: %s",+ session_id,+ str(e),+ )diff --git a/src/agentscope/app/_service/_session_projection.py b/src/agentscope/app/_service/_session_projection.pynew file mode 100644index 000000000..8e7181595--- /dev/null+++ b/src/agentscope/app/_service/_session_projection.py@@ -0,0 +1,184 @@+# -*- coding: utf-8 -*-+"""Generic cross-session UI projection primitive.++A *projection* mirrors a UI card owned by one session onto another+session's event stream, so a client subscribed only to the target+session can render and resolve it. The canonical use is team HITL: a+worker (member) session parks on a tool call awaiting confirmation in+its own session — invisible to a client watching only the *leader* —+so the pending request is projected onto the leader.++This class is **pure mechanism**: it knows nothing about teams,+workers, leaders, or HITL. It is the reusable substrate every such+feature shares — a durable per-session hash plus a live notification —+so a new projection feature is a small strategy object (an+``EventProjector``) over this primitive, not a new bus wrapper class.++Backed entirely by the message-bus generic registry primitives+(``registry_*``) and :meth:`MessageBus.session_publish_event`; no+business methods are added to ``MessageBus``. Key conventions live in+:class:`~agentscope.app.message_bus.MessageBusKeys`.++Persistence model:++- The Redis hash is the **only durable** record of a projected card —+ the target session's event channel (replay log + pub/sub) is not+ durable across runs. It carries **no TTL**: a legitimate card can+ stay pending indefinitely. Authoritative truth for whether a card is+ still live lives in the *owning* session's own state; stale hash+ entries are healed by reconcile-on-read at SSE replay time, not by+ expiry.+- ``kind`` partitions the hash so one target session can host several+ independent feeds (HITL, progress, errors, …) without collision.+"""+import json+from typing import TYPE_CHECKING++from ..message_bus import MessageBusKeys+from ...event import CustomEvent++if TYPE_CHECKING:+ from ..message_bus import MessageBus+++class SessionProjection:+ """Durable per-session store of UI cards projected from elsewhere.++ A thin stateless wrapper around the message bus — construct one+ wherever needed (it holds only a bus reference). Entries are grouped+ per ``(target_session_id, kind)``; within a feed each entry is keyed+ by a caller-chosen ``entry_id``.++ Live notification piggybacks on the target session's existing event+ channel via :meth:`publish`, so front-ends receive updates over the+ same ``GET /sessions/{sid}/stream`` SSE connection they already use.+ """++ def __init__(self, message_bus: "MessageBus") -> None:+ """Bind the message bus.++ Args:+ message_bus (`MessageBus`):+ Application message bus; only its generic ``registry_*``+ primitives and :meth:`session_publish_event` are used.+ """+ self._bus = message_bus++ async def upsert(+ self,+ target_sid: str,+ kind: str,+ entry_id: str,+ payload: dict,+ ) -> None:+ """Persist (or overwrite) one projected entry.++ Args:+ target_sid (`str`):+ The session the entry is projected onto.+ kind (`str`):+ The projection feed (e.g. ``"subagent_hitl"``).+ entry_id (`str`):+ Identity of the entry within the feed.+ payload (`dict`):+ The entry to store (JSON-serializable).+ """+ await self._bus.registry_set(+ MessageBusKeys.projection_namespace(target_sid),+ MessageBusKeys.projection_field(kind, entry_id),+ json.dumps(payload),+ )++ async def delete(+ self,+ target_sid: str,+ kind: str,+ entry_id: str,+ ) -> None:+ """Remove one projected entry.++ Idempotent: a no-op when the entry is already gone.++ Args:+ target_sid (`str`):+ The session the entry was projected onto.+ kind (`str`):+ The projection feed.+ entry_id (`str`):+ Identity of the entry within the feed.+ """+ await self._bus.registry_del(+ MessageBusKeys.projection_namespace(target_sid),+ MessageBusKeys.projection_field(kind, entry_id),+ )++ async def list(self, target_sid: str, kind: str) -> list[dict]:+ """Return every entry in one feed for a target session.++ Args:+ target_sid (`str`):+ The session whose projections to read.+ kind (`str`):+ The projection feed to filter by.++ Returns:+ `list[dict]`:+ All stored payloads in the feed; empty when none.+ """+ raw = await self._bus.registry_getall(+ MessageBusKeys.projection_namespace(target_sid),+ )+ prefix = MessageBusKeys.projection_field_prefix(kind)+ return [+ json.loads(value)+ for field, value in raw.items()+ if field.startswith(prefix)+ ]++ async def purge(self, target_sid: str, kind: str | None = None) -> None:+ """Drop projected entries for a target session.++ Args:+ target_sid (`str`):+ The session to purge.+ kind (`str | None`, optional):+ When given, drop only that feed's entries (preserving+ other feeds on the same session). When ``None``, drop+ the session's entire projection store in one shot.+ """+ if kind is None:+ await self._bus.registry_drop(+ MessageBusKeys.projection_namespace(target_sid),+ )+ return+ ns = MessageBusKeys.projection_namespace(target_sid)+ prefix = MessageBusKeys.projection_field_prefix(kind)+ raw = await self._bus.registry_getall(ns)+ for field in raw:+ if field.startswith(prefix):+ await self._bus.registry_del(ns, field)++ async def publish(+ self,+ target_sid: str,+ event_name: str,+ value: dict,+ ) -> None:+ """Send a live ``CustomEvent`` to a target session's channel.++ Notifies front-ends subscribed to the target session that a+ projected card should be rendered or cleared.++ Args:+ target_sid (`str`):+ The session to notify.+ event_name (`str`):+ The ``CustomEvent.name`` carried to the front-end.+ value (`dict`):+ The event payload.+ """+ custom = CustomEvent(name=event_name, value=value)+ await self._bus.session_publish_event(+ target_sid,+ custom.model_dump(mode="json"),+ )diff --git a/src/agentscope/app/_types.py b/src/agentscope/app/_types.pyindex fa01c4b45..a4180df01 100644--- a/src/agentscope/app/_types.py+++ b/src/agentscope/app/_types.py@@ -1,15 +1,21 @@# -*- coding: utf-8 -*-"""Shared type aliases for the agentscope app layer."""from collections.abc import Awaitable, Callable+from typing import TYPE_CHECKING, Protocolfrom pydantic import BaseModel, Fieldfrom ..agent import ContextConfig, ReActConfig+from ..event import AgentEventfrom ..middleware import MiddlewareBasefrom ..permission import PermissionContextfrom ..state import TaskContextfrom ..tool import ToolBase+if TYPE_CHECKING:+ from ._service._session_projection import SessionProjection+ from .storage import AgentRecord, SessionRecord+AgentMiddlewareFactory = Callable[[str, str, str],@@ -26,6 +32,54 @@ AgentToolFactory = Callable[# awaitable of :class:`~agentscope.tool.ToolBase` instances.+class EventProjector(Protocol):+ """Strategy that projects events from one session onto another.++ Each projector owns one cross-session UI feed (HITL, progress,+ errors, …). :class:`~agentscope.app._service.ChatService` calls+ every registered projector once per event produced by a run; a+ projector decides whether the event is relevant and, if so, mirrors+ it onto the owning session's target via the shared+ :class:`SessionProjection` primitive. Adding a feed means adding a+ projector — no new bus wrapper, dispatcher, or manager.++ Service dependencies a projector needs (e.g. storage, to resolve the+ team a worker belongs to) are its own concern, injected at+ construction. Only per-run request data is passed to+ :meth:`maybe_project`.+ """++ async def maybe_project(+ self,+ user_id: str,+ session_record: "SessionRecord",+ agent_record: "AgentRecord",+ event: AgentEvent,+ projection: "SessionProjection",+ ) -> None:+ """Project ``event`` if it is relevant to this feed.++ Implementations must be a no-op for irrelevant events and+ sessions. They should not raise for ordinary "not applicable"+ cases; ``ChatService`` guards the call with a catch-all so a+ projection failure never tears down the producing run, but+ projectors should not rely on that for control flow.++ Args:+ user_id (`str`):+ The owner of the running session.+ session_record (`SessionRecord`):+ The currently-running session's record.+ agent_record (`AgentRecord`):+ The currently-running agent's record.+ event (`AgentEvent`):+ The event just published to this session's channel.+ projection (`SessionProjection`):+ Shared primitive used to write the durable entry and the+ live notification.+ """++class SubAgentTemplate(BaseModel):"""A reusable blueprint for sub-agent creation within a team.diff --git a/src/agentscope/app/message_bus/__init__.py b/src/agentscope/app/message_bus/__init__.pyindex 147ec9dc5..9df5f8782 100644--- a/src/agentscope/app/message_bus/__init__.py+++ b/src/agentscope/app/message_bus/__init__.py@@ -2,9 +2,11 @@"""The message bus module — live transport for cross-session messages."""from ._base import MessageBus+from ._keys import MessageBusKeysfrom ._redis_message_bus import RedisMessageBus__all__ = ["MessageBus",+ "MessageBusKeys","RedisMessageBus",]diff --git a/src/agentscope/app/message_bus/_base.py b/src/agentscope/app/message_bus/_base.pyindex f818c4ce7..6bd6491f6 100644--- a/src/agentscope/app/message_bus/_base.py+++ b/src/agentscope/app/message_bus/_base.py@@ -45,6 +45,8 @@ from collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanagerfrom typing import Any, Callable, Self+from ._keys import MessageBusKeys+class MessageBus(ABC): # pylint: disable=too-many-public-methods"""Abstract base class for live message transport.@@ -750,11 +752,16 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods# Wakeup ----------------------------------------------------------_WAKEUP_QUEUE_KEY = "agentscope:wakeups"- """Shared wake-up queue (durable Redis Stream)."""+ """Shared run-trigger queue (durable Redis Stream).++ Despite the historical name, this carries *all* dispatcher-driven+ run triggers, not just idle wake-ups — each entry's ``kind`` tells+ the dispatcher how to spawn the run (see :meth:`enqueue_wakeup` /+ :meth:`enqueue_input`)."""_WAKEUP_SIGNAL_KEY = "agentscope:wakeup_signal""""Shared Pub/Sub channel that nudges dispatchers to drain the- wake-up queue."""+ run-trigger queue."""async def enqueue_wakeup(self,@@ -762,7 +769,7 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodssession_id: str,agent_id: str,) -> None:- """Enqueue a wake-up request and signal dispatchers.+ """Enqueue an idle-session wake-up and signal dispatchers.Producers (e.g. ``TeamSay``, ``AgentCreate``, the schedulertrigger, or the BG-tool completion watcher) call this after@@ -771,6 +778,11 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodson each signal and starts a chat run for any session thatis not currently active.+ Equivalent to :meth:`enqueue_input` with+ ``kind=MessageBusKeys.WAKEUP_KIND_WAKE`` and no input; kept as the+ explicit, narrowly-typed entry point for the common idle-wake+ case.+Args:user_id (`str`):The owning user id.@@ -779,12 +791,59 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodsagent_id (`str`):The agent id that owns the session."""+ await self.enqueue_input(+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_WAKE,+ inputs=None,+ )++ async def enqueue_input(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ *,+ kind: str,+ inputs: dict | None = None,+ ) -> None:+ """Enqueue a typed run trigger and signal dispatchers.++ The generalised producer behind every dispatcher-driven run.+ It makes the durable queue a per-session input mailbox: ``wake``+ triggers drain inbox content (no input), ``resume`` triggers+ carry a serialised human-in-the-loop result so the parked run+ can continue. Routing all triggers through this single queue+ keeps the :class:`WakeupDispatcher` the sole spawn site, which+ is what makes concurrent-spawn races (two writers contending for+ one session's run slot) structurally impossible.++ Args:+ user_id (`str`):+ The owning user id.+ session_id (`str`):+ The session to trigger a run for.+ agent_id (`str`):+ The agent id that owns the session.+ kind (`str`):+ The trigger kind — :attr:`MessageBusKeys.WAKEUP_KIND_WAKE`+ or :attr:`MessageBusKeys.WAKEUP_KIND_RESUME`. Governs how+ the dispatcher handles a busy session and what it passes+ as ``input_msg``.+ inputs (`dict | None`, optional):+ The JSON-serialised input event to feed the run (e.g. a+ ``UserConfirmResultEvent`` dump) for ``resume`` triggers.+ ``None`` for ``wake`` triggers.+ """await self.queue_push(self._WAKEUP_QUEUE_KEY,{"user_id": user_id,"session_id": session_id,"agent_id": agent_id,+ "kind": kind,+ "input": inputs,},)await self.publish(self._WAKEUP_SIGNAL_KEY, {})@@ -793,7 +852,7 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodsself,max_count: int = 64,) -> list[dict]:- """Drain pending wake-up entries.+ """Drain pending run-trigger entries.Args:max_count (`int`, defaults to ``64``):@@ -801,8 +860,11 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodsReturns:`list[dict]`:- Entries shaped ``{"user_id", "session_id",- "agent_id"}`` in enqueue order.+ Entries shaped ``{"user_id", "session_id", "agent_id",+ "kind", "input"}`` in enqueue order. Entries produced by+ older code paths may omit ``kind``/``input``; consumers+ should treat a missing ``kind`` as+ :attr:`MessageBusKeys.WAKEUP_KIND_WAKE`."""entries = await self.queue_drain(self._WAKEUP_QUEUE_KEY,diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.pynew file mode 100644index 000000000..eec57b4c6--- /dev/null+++ b/src/agentscope/app/message_bus/_keys.py@@ -0,0 +1,104 @@+# -*- coding: utf-8 -*-+"""Centralised registry of message-bus key/namespace conventions used+by application-layer services.++:class:`~agentscope.app.message_bus.MessageBus` itself stays+domain-agnostic — it exposes only generic primitives+(``publish`` / ``subscribe`` / ``queue_*`` / ``log_*`` / ``registry_*``+/ ``acquire_lock``). All business-specific key formats live here so+they can be audited, migrated, and (eventually) ported off from the+current scattered ``_BASE_…_KEY`` constants on ``MessageBus``.++Add new business keys here as needed. As legacy keys are migrated off+``MessageBus``, they should move into this class as well.+"""+++class MessageBusKeys:+ """Application-layer key conventions for the message bus."""++ # ------------------------------------------------------------------+ # Run-trigger queue — the discriminator carried by each entry on the+ # shared trigger queue, telling the dispatcher how to spawn the run.+ # Centralised here (rather than on ``MessageBus``) so the bus stays+ # free of business vocabulary.+ # ------------------------------------------------------------------++ WAKEUP_KIND_WAKE = "wake"+ """Trigger kind: wake an *idle* session to drain pending inbox+ content. The dispatcher spawns the run with ``input_msg=None`` and+ skips the session entirely while it is already running."""++ WAKEUP_KIND_RESUME = "resume"+ """Trigger kind: resume a session parked on an awaiting tool call by+ feeding it a human-in-the-loop result. The dispatcher spawns the run+ with the carried ``input`` event and — unlike ``wake`` — must *not*+ drop the entry while the session is running; it re-queues until the+ parked run releases its lock."""++ # ------------------------------------------------------------------+ # Cross-session UI projection — a generic per-session Redis-hash+ # store onto which one session can project UI cards owned by another+ # (e.g. a team member's pending HITL request projected onto its+ # leader). The ``kind`` prefix on each field lets a single target+ # session carry several independent projection feeds without key+ # collisions, so new projection features reuse this store rather+ # than minting their own.+ # ------------------------------------------------------------------++ _PROJECTION_NS = "agentscope:session:projection:{sid}"+ """Redis-hash namespace key template (per *target* session id)."""++ @classmethod+ def projection_namespace(cls, target_session_id: str) -> str:+ """Return the registry namespace for a session's projections.++ Args:+ target_session_id (`str`):+ The session the entries are projected onto (the session+ whose UI renders them).++ Returns:+ `str`:+ The Redis-hash namespace key.+ """+ return cls._PROJECTION_NS.format(sid=target_session_id)++ @staticmethod+ def projection_field(kind: str, entry_id: str) -> str:+ """Return the hash field key for a single projected entry.++ The ``kind`` prefix namespaces the field so different projection+ feeds sharing one target session never collide, and so a feed+ can be listed/purged by scanning for its prefix.++ Args:+ kind (`str`):+ The projection feed this entry belongs to (e.g.+ ``"subagent_hitl"``).+ entry_id (`str`):+ The entry's identity within the feed, unique per+ ``kind`` (e.g. ``"{worker_session_id}:{reply_id}"``).++ Returns:+ `str`:+ The hash field key, ``"{kind}:{entry_id}"``.+ """+ return f"{kind}:{entry_id}"++ @staticmethod+ def projection_field_prefix(kind: str) -> str:+ """Return the field-key prefix that identifies one feed.++ Used to filter :meth:`MessageBus.registry_getall` down to a+ single ``kind`` when listing or purging.++ Args:+ kind (`str`):+ The projection feed.++ Returns:+ `str`:+ The field-key prefix, ``"{kind}:"``.+ """+ return f"{kind}:"diff --git a/tests/service_message_bus_test.py b/tests/service_message_bus_test.pyindex 309462280..bbf6455dc 100644--- a/tests/service_message_bus_test.py+++ b/tests/service_message_bus_test.py@@ -355,12 +355,20 @@ class TestInboxAndWakeupHelpers(IsolatedAsyncioTestCase):# Signal fired.self.assertEqual(len(received), 1)- # Queue holds the structured entry.+ # Queue holds the structured entry. ``enqueue_wakeup`` is the+ # idle-wake shortcut, so the entry carries ``kind="wake"`` and a+ # null input alongside the routing fields.entries = await self.bus.dequeue_wakeups(max_count=10)self.assertEqual(len(entries), 1)self.assertEqual(entries[0],- {"user_id": "u", "session_id": "s", "agent_id": "a"},+ {+ "user_id": "u",+ "session_id": "s",+ "agent_id": "a",+ "kind": "wake",+ "input": None,+ },)diff --git a/tests/service_scheduler_test.py b/tests/service_scheduler_test.pyindex f2e0d9c97..8dc9af93b 100644--- a/tests/service_scheduler_test.py+++ b/tests/service_scheduler_test.py@@ -177,6 +177,8 @@ class TestSchedulerFireDelivery(_SchedulerFireTestBase):"session_id": session.id,"agent_id": record.agent_id,"user_id": record.user_id,+ "kind": "wake",+ "input": None,},)@@ -231,11 +233,15 @@ class TestSchedulerFireStatefulMode(_SchedulerFireTestBase):"session_id": sessions[0].id,"agent_id": record.agent_id,"user_id": record.user_id,+ "kind": "wake",+ "input": None,},{"session_id": sessions[0].id,"agent_id": record.agent_id,"user_id": record.user_id,+ "kind": "wake",+ "input": None,},],)diff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.pyindex 94bac2aff..093e0582f 100644--- a/tests/service_team_tools_test.py+++ b/tests/service_team_tools_test.py@@ -307,6 +307,8 @@ class TestAgentCreate(_TeamToolsTestBase):"session_id": worker_sessions[0].id,"agent_id": worker_agent_id,"user_id": self.user_id,+ "kind": "wake",+ "input": None,},)@@ -931,6 +933,8 @@ class TestTeamSay(_TeamToolsTestBase):"session_id": target_sid,"agent_id": target_aid,"user_id": self.user_id,+ "kind": "wake",+ "input": None,},],)@@ -1095,6 +1099,8 @@ class TestTeamSay(_TeamToolsTestBase):"session_id": self.leader_session.id,"agent_id": self.leader_agent.id,"user_id": self.user_id,+ "kind": "wake",+ "input": None,},],)diff --git a/tests/service_wakeup_dispatcher_test.py b/tests/service_wakeup_dispatcher_test.pyindex 6a2aa53ae..05c8eb993 100644--- a/tests/service_wakeup_dispatcher_test.py+++ b/tests/service_wakeup_dispatcher_test.py@@ -20,7 +20,7 @@ from typing import Any, AsyncGenerator, Callablefrom unittest import IsolatedAsyncioTestCasefrom agentscope.app._manager import ChatRunRegistry, WakeupDispatcher-from agentscope.app.message_bus import MessageBus+from agentscope.app.message_bus import MessageBus, MessageBusKeysclass _FakeStorage:@@ -366,6 +366,92 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):],)+ async def test_resume_idle_spawns_with_parsed_event(self) -> None:+ """A ``resume`` trigger for an idle session spawns a run whose+ ``input_msg`` is the carried HITL event, rebuilt from its dump."""+ from agentscope.event import UserConfirmResultEvent++ bus = _FakeBus()+ chat = _FakeChatService()+ event = UserConfirmResultEvent.model_construct(+ reply_id="r1",+ confirm_results=[],+ )++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {+ "user_id": "u",+ "session_id": "w1",+ "agent_id": "wa1",+ "kind": MessageBusKeys.WAKEUP_KIND_RESUME,+ "input": event.model_dump(mode="json"),+ },+ )+ await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(len(chat.calls), 1)+ call = chat.calls[0]+ self.assertEqual(call["session_id"], "w1")+ self.assertIsInstance(call["input_msg"], UserConfirmResultEvent)+ self.assertEqual(call["input_msg"].reply_id, "r1")++ async def test_resume_running_session_requeues_until_free(self) -> None:+ """A ``resume`` whose target is still running is NOT dropped: it+ is re-queued (with backoff) and dispatched once the session lock+ releases. This is the structural fix for the parked-run 409 race.+ """+ from agentscope.event import UserConfirmResultEvent++ bus = _FakeBus()+ chat = _FakeChatService()+ lock_key = MessageBus._SESSION_LOCK_KEY.format(sid="w1")+ bus._locks.add(lock_key) # session is busy finishing its park tail+ event = UserConfirmResultEvent.model_construct(+ reply_id="r1",+ confirm_results=[],+ )++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await bus.queue_push(+ MessageBus._WAKEUP_QUEUE_KEY,+ {+ "user_id": "u",+ "session_id": "w1",+ "agent_id": "wa1",+ "kind": MessageBusKeys.WAKEUP_KIND_RESUME,+ "input": event.model_dump(mode="json"),+ },+ )+ await bus.publish(MessageBus._WAKEUP_SIGNAL_KEY, {})++ # While locked, the resume must keep deferring — no run yet.+ await asyncio.sleep(0.25)+ self.assertEqual(chat.calls, [])++ # Release the lock; the re-queued resume now lands.+ bus._locks.discard(lock_key)+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(len(chat.calls), 1)+ self.assertEqual(chat.calls[0]["session_id"], "w1")+ self.assertIsInstance(+ chat.calls[0]["input_msg"],+ UserConfirmResultEvent,+ )+class TestWakeupDispatcherLifecycle(IsolatedAsyncioTestCase):"""Tests covering the ``__aenter__`` / ``__aexit__`` ACM behaviour."""