Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(webui): add editable server-side chat queues (#2236)
qbc2350af908be8
diff --git a/examples/web_ui/frontend/src/api/chat.ts b/examples/web_ui/frontend/src/api/chat.tsindex cdee46222..7fae0c264 100644--- a/examples/web_ui/frontend/src/api/chat.ts+++ b/examples/web_ui/frontend/src/api/chat.ts@@ -1,8 +1,24 @@+import type { Msg } from '@agentscope-ai/agentscope/message';+import { client } from './client';import type { ChatRequest } from './types';+export interface ChatQueueItem {+ /** Stable business id used by queue mutation endpoints. */+ id: string;+ /** UTC ISO-8601 timestamp recorded when the item was queued. */+ created_at: string;+ /** One message or an ordered message group executed as one turn. */+ input: Msg | Msg[];+}++export interface ChatQueueResponse {+ /** Complete editable pending queue in FIFO order. */+ items: ChatQueueItem[];+}+/**- * Chat API — fire-and-forget trigger for chat runs.+ * Chat API — accept queued user turns and fire-and-forget control triggers.** Events produced by the run are delivered via the session's SSE* stream endpoint (``GET /sessions/{sid}/stream``), not in the@@ -18,8 +34,71 @@ export const chatApi = {* stream to receive the resulting events.** @param body - The chat request payload.- * @returns A confirmation object ``{ status, session_id }``.+ * @returns Acceptance status (``queued`` for ordinary user turns).*/trigger: (body: ChatRequest) =>- client.post<{ status: string; session_id: string }>('/chat/', body),+ client.post<{+ status: 'started' | 'queued';+ session_id: string;+ queue_item_id: string | null;+ }>('/chat/', body),++ /**+ * Read the complete editable pending queue.+ *+ * @param agentId - Agent that owns the target session.+ * @param sessionId - Session whose FIFO should be read.+ * @param silent - Suppress global error notifications for repair polling.+ * @returns Current pending items in FIFO order.+ */+ queue: (agentId: string, sessionId: string, silent = false) =>+ client.get<ChatQueueResponse>(+ '/chat/queue',+ {+ agent_id: agentId,+ session_id: sessionId,+ },+ { silent },+ ),++ /**+ * Replace one item that has not started execution.+ *+ * @param itemId - Stable id of the pending item.+ * @param body - Target ownership fields and replacement input.+ * @returns Complete queue snapshot after the update.+ */+ updateQueued: (+ itemId: string,+ body: { agent_id: string; session_id: string; input: Msg | Msg[] },+ ) => client.patch<ChatQueueResponse>(`/chat/queue/${encodeURIComponent(itemId)}`, body),++ /**+ * Delete one item that has not started execution.+ *+ * @param itemId - Stable id of the pending item.+ * @param agentId - Agent that owns the target session.+ * @param sessionId - Session whose item should be deleted.+ * @returns Complete queue snapshot after deletion.+ */+ deleteQueued: (itemId: string, agentId: string, sessionId: string) =>+ client.delete<ChatQueueResponse>(`/chat/queue/${encodeURIComponent(itemId)}`, {+ agent_id: agentId,+ session_id: sessionId,+ }),++ /**+ * Apply an exact permutation of the current pending queue.+ *+ * @param agentId - Agent that owns the target session.+ * @param sessionId - Session whose FIFO should be reordered.+ * @param itemIds - All pending item ids in the desired order.+ * @returns Complete queue snapshot after reordering.+ */+ reorderQueued: (agentId: string, sessionId: string, itemIds: string[]) =>+ client.patch<ChatQueueResponse>('/chat/queue/order', {+ agent_id: agentId,+ session_id: sessionId,+ item_ids: itemIds,+ }),};diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsxindex cdc61294b..bbcbf2298 100644--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx@@ -9,15 +9,17 @@ import {import { GitBranch, TriangleAlert } from 'lucide-react';import React, { useEffect, useMemo, useState } from 'react';-import { Button } from '../ui/button';-import { DiffStats } from './tool-renderers/_shared';import type { GitStatus } from '@/api';+import type { ChatQueueItem } from '@/api/chat';import { ASMessageBubble } from '@/components/chat/ASMessageBubble.tsx';import { ConfirmCard } from '@/components/chat/ConfirmCard.tsx';import { FlipCard } from '@/components/chat/FlipCard.tsx';+import { QueuedMessages } from '@/components/chat/QueuedMessages.tsx';import { TextInput } from '@/components/chat/TextInput.tsx';+import { DiffStats } from '@/components/chat/tool-renderers/_shared';import { WorkingDirectoryDialog } from '@/components/dialog/WorkingDirectoryDialog';import { Alert, AlertAction, AlertDescription, AlertTitle } from '@/components/ui/alert.tsx';+import { Button } from '@/components/ui/button';import { Marker, MarkerContent } from '@/components/ui/marker';import {MessageScroller,@@ -70,12 +72,16 @@ interface ChatContentProps {loading?: boolean;/*** Reply lifecycle phase from ``useMessages`` — forwarded to- * ``TextInput`` so the shared voice / send / stop button can pick its- * icon, tooltip, disabled state and click handler from one source.+ * ``TextInput`` so it can show a separate Stop action while keeping+ * Send available for queued turns and coordinate realtime voice.*/phase: ReplyPhase;+ /** Number of locally submitted user turns waiting to start. */+ queuedCount: number;+ queuedItems: ChatQueueItem[];+ queueReorderDisabled: boolean;disabled: boolean;- onSend: (content: ContentBlock[]) => void;+ onSend: (content: ContentBlock[]) => Promise<void> | void;onUserConfirm: (toolCall: ToolCallBlock,confirm: boolean,@@ -86,6 +92,10 @@ interface ChatContentProps {className?: string;/** Called when the user clicks the stop button. */onInterrupt?: () => void;+ onUpdateQueued: (itemId: string, text: string) => Promise<void>;+ onDeleteQueued: (itemId: string) => Promise<void>;+ onMoveQueued: (itemId: string, direction: -1 | 1) => Promise<void>;+ onReorderQueued: (itemIds: string[]) => Promise<void>;voiceState?: RealtimeConnectionState;onVoiceToggle?: () => void;voiceDisabled?: boolean;@@ -119,12 +129,19 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({msgs,loading = false,phase,+ queuedCount,+ queuedItems,+ queueReorderDisabled,disabled,onSend,onUserConfirm,autoComplete,className,onInterrupt,+ onUpdateQueued,+ onDeleteQueued,+ onMoveQueued,+ onReorderQueued,voiceState,onVoiceToggle,voiceDisabled,@@ -238,19 +255,23 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({<Buttonsize={'xs'}onClick={() => {- onSend([- {- id: crypto.randomUUID(),- type: 'text',- text: t(- 'chat.maxItersExceeded.continue',- ),- created_at:- new Date().toISOString(),- finished_at:- new Date().toISOString(),- } as TextBlock,- ]);+ void Promise.resolve(+ onSend([+ {+ id: crypto.randomUUID(),+ type: 'text',+ text: t(+ 'chat.maxItersExceeded.continue',+ ),+ created_at:+ new Date().toISOString(),+ finished_at:+ new Date().toISOString(),+ } as TextBlock,+ ]),+ ).catch(() => {+ // The send handler reports the failure.+ });}}>{t('chat.maxItersExceeded.continue')}@@ -288,12 +309,21 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({footerSlot)}</FlipCard>+ <QueuedMessages+ items={queuedItems}+ reorderDisabled={queueReorderDisabled}+ onUpdate={onUpdateQueued}+ onDelete={onDeleteQueued}+ onMove={onMoveQueued}+ onReorder={onReorderQueued}+ />{/* Concentric radii: the pill stays rounded-[28px] on all fourcorners and floats on this surface, whose own radius is28 + the 4px padding. Matching them is what keeps the twoedges parallel — a plain rectangle here would show thepill's corners cutting into it. */}<TextInput+ key={JSON.stringify([agentId, sessionId])}className="min-w-full max-w-full w-full rounded-[32px] bg-muted p-1"onSend={onSend}disabled={disabled}@@ -301,6 +331,7 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({allowedInputTypes={allowedInputTypes}fileProcessor={fileProcessor}phase={phase}+ queuedCount={queuedCount}onInterrupt={onInterrupt}voiceState={voiceState}onVoiceToggle={onVoiceToggle}diff --git a/examples/web_ui/frontend/src/components/chat/QueuedMessages.tsx b/examples/web_ui/frontend/src/components/chat/QueuedMessages.tsxnew file mode 100644index 000000000..967acf599--- /dev/null+++ b/examples/web_ui/frontend/src/components/chat/QueuedMessages.tsx@@ -0,0 +1,242 @@+import { getTextContent } from '@agentscope-ai/agentscope/message';+import { ArrowDown, ArrowUp, Check, GripVertical, Loader2, Pencil, Trash2, X } from 'lucide-react';+import { type ReactNode, useState } from 'react';++import type { ChatQueueItem } from '@/api/chat';+import { Button } from '@/components/ui/button';+import { Textarea } from '@/components/ui/textarea';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { useTranslation } from '@/i18n/useI18n';+import { cn } from '@/lib/utils';++interface QueuedMessagesProps {+ items: ChatQueueItem[];+ reorderDisabled: boolean;+ onUpdate: (itemId: string, text: string) => Promise<void>;+ onDelete: (itemId: string) => Promise<void>;+ onMove: (itemId: string, direction: -1 | 1) => Promise<void>;+ onReorder: (itemIds: string[]) => Promise<void>;+}++const itemText = (item: ChatQueueItem): string => {+ const messages = Array.isArray(item.input) ? item.input : [item.input];+ return messages+ .map((message) => getTextContent(message))+ .filter(Boolean)+ .join('\n');+};++interface QueueActionButtonProps {+ label: string;+ disabled?: boolean;+ onClick: () => void;+ children: ReactNode;+}++/** Keep icon-only queue actions consistent and accessible. */+function QueueActionButton({ label, disabled, onClick, children }: QueueActionButtonProps) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ disabled={disabled}+ aria-label={label}+ onClick={onClick}+ >+ {children}+ </Button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ );+}++/** Editable FIFO shown immediately above the composer. */+export function QueuedMessages({+ items,+ reorderDisabled,+ onUpdate,+ onDelete,+ onMove,+ onReorder,+}: QueuedMessagesProps) {+ const { t } = useTranslation();+ const [editingId, setEditingId] = useState<string | null>(null);+ const [draft, setDraft] = useState('');+ const [busyId, setBusyId] = useState<string | null>(null);+ const [draggedId, setDraggedId] = useState<string | null>(null);+ const [dropTargetId, setDropTargetId] = useState<string | null>(null);++ if (items.length === 0) return null;++ const run = async (itemId: string, action: () => Promise<void>) => {+ setBusyId(itemId);+ try {+ await action();+ } catch {+ // The shared API client already displays the server detail.+ // Keep the item/draft visible so the user can retry.+ } finally {+ setBusyId(null);+ }+ };++ const dropBefore = (targetId: string) => {+ if (reorderDisabled || !draggedId || draggedId === targetId) return;+ const reordered = [...items];+ const sourceIndex = reordered.findIndex((item) => item.id === draggedId);+ const targetIndex = reordered.findIndex((item) => item.id === targetId);+ if (sourceIndex < 0 || targetIndex < 0) return;+ const [moved] = reordered.splice(sourceIndex, 1);+ reordered.splice(targetIndex, 0, moved);+ void run(draggedId, () => onReorder(reordered.map((item) => item.id)));+ setDraggedId(null);+ setDropTargetId(null);+ };++ return (+ <div className="mb-2 max-h-52 overflow-y-auto rounded-xl border bg-background/95 p-2 shadow-sm">+ <div className="px-1 pb-1 text-xs font-medium text-muted-foreground">+ {t('chatQueue.title', { count: items.length })}+ </div>+ <div className="space-y-1">+ {items.map((item, index) => {+ const editing = editingId === item.id;+ // Optimistic ids are local-only and cannot be sent to mutation+ // endpoints until POST /chat returns the stable server id.+ const busy = busyId === item.id || item.id.startsWith('optimistic:');+ const reorderBusy = busy || reorderDisabled;+ const editable = !Array.isArray(item.input);+ return (+ <div+ key={item.id}+ onDragOver={(event) => {+ if (reorderDisabled) return;+ event.preventDefault();+ event.dataTransfer.dropEffect = 'move';+ setDropTargetId(item.id);+ }}+ onDragLeave={() =>+ setDropTargetId((current) => (current === item.id ? null : current))+ }+ onDrop={(event) => {+ event.preventDefault();+ dropBefore(item.id);+ }}+ className={cn(+ 'flex items-center gap-1 rounded-lg border px-2 py-1.5 transition-colors',+ dropTargetId === item.id+ ? 'border-primary bg-primary/5'+ : 'border-transparent bg-muted/50',+ )}+ >+ <div+ draggable={!editing && !reorderBusy}+ onDragStart={(event) => {+ setDraggedId(item.id);+ event.dataTransfer.effectAllowed = 'move';+ event.dataTransfer.setData('text/plain', item.id);+ }}+ onDragEnd={() => {+ setDraggedId(null);+ setDropTargetId(null);+ }}+ className={cn(+ 'touch-none text-muted-foreground',+ reorderBusy+ ? 'cursor-not-allowed opacity-50'+ : 'cursor-grab active:cursor-grabbing',+ )}+ title={t('chatQueue.drag')}+ aria-hidden="true"+ >+ <GripVertical className="size-4" />+ </div>+ <span className="w-5 shrink-0 text-center text-xs text-muted-foreground">+ {index + 1}+ </span>+ {editing ? (+ <Textarea+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ rows={2}+ autoFocus+ aria-label={t('chatQueue.edit')}+ className="min-h-0 min-w-0 flex-1 resize-none rounded-md bg-background px-2 py-1 text-sm"+ />+ ) : (+ <p+ className="min-w-0 flex-1 truncate text-sm"+ title={itemText(item)}+ >+ {itemText(item) || t('chatQueue.attachmentOnly')}+ </p>+ )}++ {busy ? (+ <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" />+ ) : editing ? (+ <>+ <QueueActionButton+ disabled={!draft.trim()}+ label={t('chatQueue.save')}+ onClick={() =>+ void run(item.id, async () => {+ await onUpdate(item.id, draft.trim());+ setEditingId(null);+ })+ }+ >+ <Check className="size-3.5" />+ </QueueActionButton>+ <QueueActionButton+ label={t('chatQueue.cancel')}+ onClick={() => setEditingId(null)}+ >+ <X className="size-3.5" />+ </QueueActionButton>+ </>+ ) : (+ <>+ <QueueActionButton+ disabled={reorderBusy || index === 0}+ label={t('chatQueue.moveUp')}+ onClick={() => void run(item.id, () => onMove(item.id, -1))}+ >+ <ArrowUp className="size-3.5" />+ </QueueActionButton>+ <QueueActionButton+ disabled={reorderBusy || index === items.length - 1}+ label={t('chatQueue.moveDown')}+ onClick={() => void run(item.id, () => onMove(item.id, 1))}+ >+ <ArrowDown className="size-3.5" />+ </QueueActionButton>+ <QueueActionButton+ disabled={!editable}+ label={t('chatQueue.edit')}+ onClick={() => {+ setDraft(itemText(item));+ setEditingId(item.id);+ }}+ >+ <Pencil className="size-3.5" />+ </QueueActionButton>+ <QueueActionButton+ label={t('chatQueue.delete')}+ onClick={() => void run(item.id, () => onDelete(item.id))}+ >+ <Trash2 className="size-3.5 text-destructive" />+ </QueueActionButton>+ </>+ )}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/examples/web_ui/frontend/src/components/chat/TextInput.tsx b/examples/web_ui/frontend/src/components/chat/TextInput.tsxindex 3b87c3976..b40fd0b39 100644--- a/examples/web_ui/frontend/src/components/chat/TextInput.tsx+++ b/examples/web_ui/frontend/src/components/chat/TextInput.tsx@@ -1,13 +1,13 @@import type { ContentBlock, TextBlock } from '@agentscope-ai/agentscope/message';import {AudioLines,- Paperclip,+ ArrowUp,+ FileText,Loader2,+ Paperclip,Square,type LucideIcon,XIcon,- FileText,- ArrowUp,} from 'lucide-react';import mime from 'mime';import React, {@@ -51,7 +51,7 @@ interface ProcessedFile {}interface TextInputProps {- onSend: (blocks: ContentBlock[]) => void;+ onSend: (blocks: ContentBlock[]) => Promise<void> | void;placeholder?: string;autoComplete?: (input: string) => string | null;disabled?: boolean;@@ -78,13 +78,13 @@ interface TextInputProps {*/fileProcessor: (file: File) => Promise<ContentBlock | null>;/**- * The current reply lifecycle phase from ``useMessages``. Drives the- * primary action button when realtime voice is inactive:- * - ``idle`` — Send (enabled when there is content to send)- * - ``streaming`` — Stop (click to interrupt)- * - ``interrupting`` — Stop (disabled while the interrupt is in flight)+ * The current reply lifecycle phase from ``useMessages``. A running+ * reply adds a separate Stop action while Send remains available for+ * appending another turn to the queue.*/phase?: ReplyPhase;+ /** Number of accepted user turns that have not started a reply yet. */+ queuedCount?: number;onInterrupt?: () => void;/** Current browser realtime voice connection state. */voiceState?: RealtimeConnectionState;@@ -133,6 +133,8 @@ const TEXTAREA_PADDING_X_PX = 12;* @param root0.autoComplete - Function to provide autocomplete suggestions.* @param root0.disabled - Whether the input is disabled.* @param root0.className - Additional CSS classes for styling.+ * @param root0.queuedCount - Accepted turns waiting to start.+ * @param root0.onInterrupt - Stops the currently active reply.* @returns A TextInput component.*/export const TextInput = forwardRef<TextInputRef, TextInputProps>(@@ -146,6 +148,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(allowedInputTypes,fileProcessor,phase = 'idle',+ queuedCount = 0,onInterrupt,voiceState = 'idle',onVoiceToggle,@@ -159,6 +162,14 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(const [value, setValue] = useState('');const [files, setFiles] = useState<ProcessedFile[]>([]);const [isFocused, setIsFocused] = useState(false);+ const [submitting, setSubmitting] = useState(false);+ const mountedRef = useRef(false);+ useLayoutEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);const textareaRef = useRef<HTMLTextAreaElement>(null);const fileInputRef = useRef<HTMLInputElement>(null);const measureRef = useRef<HTMLSpanElement>(null);@@ -231,14 +242,12 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(// Enter to send message, Shift+Enter for new lineif (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {e.preventDefault();- handleSend();+ void handleSend();}};- const handleSend = () => {- // ``phase`` is guarded here rather than only on the button, since Enter- // calls this directly and would otherwise send during a running reply.- if (phase !== 'idle' || !hasContent || disabled || hasProcessing) return;+ const handleSend = async () => {+ if (!hasContent || disabled || hasProcessing || submitting) return;const blocks: ContentBlock[] = [];@@ -261,14 +270,33 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(}});- onSend?.(blocks);+ const submittedValue = value;+ const submittedFiles = files;+ setSubmitting(true);+ // Start a fresh draft immediately. If the request fails, merge the+ // submitted draft back without erasing anything typed meanwhile.setValue('');setFiles([]);+ try {+ await onSend(blocks);+ } catch {+ if (!mountedRef.current) return;+ // The API layer reports the error; restore both the failed turn+ // and any new draft content so neither is silently lost.+ setValue((current) => (current ? `${submittedValue}\n${current}` : submittedValue));+ setFiles((current) => [...submittedFiles, ...current]);+ } finally {+ if (mountedRef.current) setSubmitting(false);+ }};+ const replyActive = phase !== 'idle';+ const voiceActive = voiceState === 'active' || voiceState === 'connecting';+/**- * Primary action configuration derived from realtime voice, reply,- * and text input state. One struct keeps the JSX branch-free.+ * The primary action controls realtime voice when it is connected,+ * otherwise it sends a normal or queued text turn. A running text+ * reply gets its own Stop button so sending remains available.*/const actionButton: {icon: LucideIcon;@@ -295,29 +323,11 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(onClick: onVoiceToggle,};}- if (phase === 'streaming') {- return {- icon: Square,- tooltip: t('textInput.stop'),- disabled: false,- variant: 'default',- onClick: onInterrupt,- };- }- if (phase === 'interrupting') {- return {- icon: Square,- tooltip: t('textInput.stopping'),- disabled: true,- variant: 'default',- onClick: onInterrupt,- };- }- if (hasContent) {+ if (hasContent || replyActive || submitting) {return {- icon: ArrowUp,- tooltip: t('textInput.send'),- disabled: disabled || hasProcessing,+ icon: submitting ? Loader2 : ArrowUp,+ tooltip: replyActive ? t('textInput.queue') : t('textInput.send'),+ disabled: disabled || !hasContent || hasProcessing || submitting,variant: 'default',onClick: handleSend,};@@ -467,6 +477,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(<div className="flex shrink-0 gap-2"><div className="size-9" /><div className="size-9" />+ {replyActive && <div className="size-9" />}</div></div>@@ -551,7 +562,32 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(</TooltipContent></Tooltip>- {/* Voice / Send / Stop — driven by ``actionButton`` config */}+ {/* Keep Stop and Send separate while a reply is active:+ users can enqueue another turn without losing the+ ability to interrupt the current generation. */}+ {replyActive && !voiceActive && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="outline"+ onClick={onInterrupt}+ disabled={phase === 'interrupting'}+ size="icon-lg"+ className="shrink-0 rounded-full"+ >+ <Square className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ {phase === 'interrupting'+ ? t('textInput.stopping')+ : t('textInput.stop')}+ </TooltipContent>+ </Tooltip>+ )}++ {/* Voice or Send — driven by ``actionButton`` config. */}<Tooltip><TooltipTrigger asChild><Button@@ -569,7 +605,8 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(<actionButton.iconclassName={cn('h-4 w-4',- voiceState === 'connecting' && 'animate-spin',+ (voiceState === 'connecting' || submitting) &&+ 'animate-spin',)}/></Button>@@ -589,6 +626,15 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(</div></div></div>+ {queuedCount > 0 && (+ <div+ className="px-3 text-xs text-muted-foreground"+ role="status"+ aria-live="polite"+ >+ {t('textInput.queued', { count: queuedCount })}+ </div>+ )}</div>);},diff --git a/examples/web_ui/frontend/src/hooks/useChatQueue.ts b/examples/web_ui/frontend/src/hooks/useChatQueue.tsnew file mode 100644index 000000000..97b02fc9e--- /dev/null+++ b/examples/web_ui/frontend/src/hooks/useChatQueue.ts@@ -0,0 +1,379 @@+import type { ContentBlock, Msg, TextBlock } from '@agentscope-ai/agentscope/message';+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';++import { chatApi } from '@/api';+import type { ChatQueueItem } from '@/api/chat';+import { ApiError } from '@/api/client';++const QUEUE_REFRESH_INTERVAL_MS = 15_000;+const OPTIMISTIC_ITEM_PREFIX = 'optimistic:';++export interface ChatInputStartedValue {+ queue_item_id?: string;+ message_ids?: string[];+ queue_item?: ChatQueueItem;+}++export interface ChatInputTerminalValue {+ queue_item_id?: string;+ message_ids?: string[];+ message?: string;+}++/** Return every message carried by queue items in FIFO order. */+export const getQueueMessages = (items: ChatQueueItem[]): Msg[] =>+ items.flatMap((item) => (Array.isArray(item.input) ? item.input : [item.input]));++/**+ * Owns the editable pending-turn queue for one chat session.+ *+ * The hook keeps server snapshots, optimistic submissions, periodic repair+ * polling, and queue mutations out of the reply-stream state machine.+ */+export function useChatQueue(+ agentId: string | null,+ sessionId: string | null,+ onError: (error: Error) => void,+) {+ const [items, setItems] = useState<ChatQueueItem[]>([]);+ const [conversationMessageIds, setConversationMessageIds] = useState<Set<string>>(new Set());+ const itemsRef = useRef<ChatQueueItem[]>([]);+ const conversationMessageIdsRef = useRef<Set<string>>(new Set());+ const snapshotVersionRef = useRef(0);+ const refreshSequenceRef = useRef(0);+ // Object identity distinguishes A -> B -> A from the original A visit.+ const session = useMemo(() => ({ agentId, sessionId }), [agentId, sessionId]);+ const activeSessionRef = useRef<typeof session | null>(null);++ useLayoutEffect(() => {+ activeSessionRef.current = session;+ return () => {+ activeSessionRef.current = null;+ };+ }, [session]);++ const updateItems = useCallback((next: ChatQueueItem[]) => {+ snapshotVersionRef.current += 1;+ itemsRef.current = next;+ setItems(next);+ }, []);++ const updateConversationMessageIds = useCallback((update: (ids: Set<string>) => void) => {+ const next = new Set(conversationMessageIdsRef.current);+ update(next);+ conversationMessageIdsRef.current = next;+ setConversationMessageIds(next);+ }, []);++ const reset = useCallback(() => {+ updateItems([]);+ updateConversationMessageIds((ids) => ids.clear());+ }, [updateConversationMessageIds, updateItems]);++ /** Apply an authoritative snapshot without erasing unaccepted local turns. */+ const applyQueueSnapshot = useCallback(+ (serverItems: ChatQueueItem[]) => {+ const optimisticItems = itemsRef.current.filter((item) =>+ item.id.startsWith(OPTIMISTIC_ITEM_PREFIX),+ );+ const serverMessageIds = new Set(+ getQueueMessages(serverItems).map((message) => message.id),+ );+ const unmatchedOptimisticItems = optimisticItems.filter(+ (item) =>+ !getQueueMessages([item]).some((message) => serverMessageIds.has(message.id)),+ );+ updateItems([...serverItems, ...unmatchedOptimisticItems]);+ },+ [updateItems],+ );++ const refreshQueue = useCallback(async () => {+ if (!agentId || !sessionId || activeSessionRef.current !== session) return;+ const requestId = ++refreshSequenceRef.current;+ const snapshotVersion = snapshotVersionRef.current;+ try {+ const response = await chatApi.queue(agentId, sessionId, true);+ if (+ activeSessionRef.current !== session ||+ requestId !== refreshSequenceRef.current ||+ snapshotVersion !== snapshotVersionRef.current+ ) {+ return;+ }+ applyQueueSnapshot(response.items);+ } catch {+ // Focus, reconnect, or the next interval retries transient failures.+ }+ }, [agentId, sessionId, session, applyQueueSnapshot]);++ const applyMutationSnapshot = useCallback(+ (serverItems: ChatQueueItem[], snapshotVersion: number) => {+ if (activeSessionRef.current !== session) return;+ if (snapshotVersion !== snapshotVersionRef.current) {+ // An SSE event or another response already changed the queue.+ // Fetch current state instead of resurrecting an older snapshot.+ void refreshQueue();+ return;+ }+ applyQueueSnapshot(serverItems);+ },+ [session, applyQueueSnapshot, refreshQueue],+ );++ useEffect(() => {+ reset();+ if (!agentId || !sessionId) return;+ void refreshQueue();+ const refreshTimer = window.setInterval(+ () => void refreshQueue(),+ QUEUE_REFRESH_INTERVAL_MS,+ );+ const refreshOnFocus = () => void refreshQueue();+ window.addEventListener('focus', refreshOnFocus);+ window.addEventListener('online', refreshOnFocus);++ return () => {+ window.clearInterval(refreshTimer);+ window.removeEventListener('focus', refreshOnFocus);+ window.removeEventListener('online', refreshOnFocus);+ };+ }, [agentId, sessionId, refreshQueue, reset]);++ const addOptimistic = useCallback(+ (message: Msg, shownInConversation: boolean): string => {+ const optimisticId = `${OPTIMISTIC_ITEM_PREFIX}${crypto.randomUUID()}`;+ if (shownInConversation) {+ updateConversationMessageIds((ids) => ids.add(message.id));+ }+ updateItems([+ ...itemsRef.current,+ {+ id: optimisticId,+ created_at: message.created_at,+ input: message,+ },+ ]);+ return optimisticId;+ },+ [updateConversationMessageIds, updateItems],+ );++ const acceptOptimistic = useCallback(+ (optimisticId: string, queueItemId: string | null) => {+ if (!queueItemId) return;+ updateItems(+ itemsRef.current.map((item) =>+ item.id === optimisticId ? { ...item, id: queueItemId } : item,+ ),+ );+ },+ [updateItems],+ );++ const rollbackOptimistic = useCallback(+ (optimisticId: string, messageId: string) => {+ updateItems(itemsRef.current.filter((item) => item.id !== optimisticId));+ updateConversationMessageIds((ids) => ids.delete(messageId));+ },+ [updateConversationMessageIds, updateItems],+ );++ /** Remove a started item and return the message payload for conversation UI. */+ const startItem = useCallback(+ (value: ChatInputStartedValue): ChatQueueItem | undefined => {+ const startedIds = new Set(value.message_ids ?? []);+ updateConversationMessageIds((ids) => {+ for (const messageId of startedIds) ids.delete(messageId);+ });+ const localItem = itemsRef.current.find(+ (item) =>+ item.id === value.queue_item_id ||+ (item.id.startsWith(OPTIMISTIC_ITEM_PREFIX) &&+ getQueueMessages([item]).some((message) => startedIds.has(message.id))),+ );+ updateItems(+ itemsRef.current.filter(+ (item) =>+ item.id !== value.queue_item_id &&+ !(+ item.id.startsWith(OPTIMISTIC_ITEM_PREFIX) &&+ getQueueMessages([item]).some((message) => startedIds.has(message.id))+ ),+ ),+ );+ return value.queue_item ?? localItem;+ },+ [updateConversationMessageIds, updateItems],+ );++ const finishItem = useCallback(+ (value: ChatInputTerminalValue) => {+ const terminalIds = new Set(value.message_ids ?? []);+ updateItems(+ itemsRef.current.filter(+ (item) =>+ item.id !== value.queue_item_id &&+ !getQueueMessages([item]).some((message) => terminalIds.has(message.id)),+ ),+ );+ updateConversationMessageIds((ids) => {+ for (const messageId of terminalIds) ids.delete(messageId);+ });+ },+ [updateConversationMessageIds, updateItems],+ );++ const updateQueued = useCallback(+ async (itemId: string, text: string) => {+ if (!agentId || !sessionId || activeSessionRef.current !== session) return;+ const item = itemsRef.current.find((candidate) => candidate.id === itemId);+ if (!item || Array.isArray(item.input)) return;++ let replacedText = false;+ const content: ContentBlock[] = [];+ for (const block of item.input.content) {+ if (block.type !== 'text') {+ content.push(block);+ } else if (!replacedText) {+ replacedText = true;+ content.push({ ...block, text });+ }+ }+ if (!replacedText) {+ const now = new Date().toISOString();+ const textBlock: TextBlock = {+ id: crypto.randomUUID(),+ type: 'text',+ text,+ created_at: now,+ finished_at: now,+ };+ content.unshift(textBlock);+ }++ const snapshotVersion = snapshotVersionRef.current;+ try {+ const response = await chatApi.updateQueued(itemId, {+ agent_id: agentId,+ session_id: sessionId,+ input: { ...item.input, content },+ });+ applyMutationSnapshot(response.items, snapshotVersion);+ } catch (error) {+ if (activeSessionRef.current === session) onError(error as Error);+ throw error;+ }+ },+ [agentId, sessionId, session, applyMutationSnapshot, onError],+ );++ const deleteQueued = useCallback(+ async (itemId: string) => {+ if (!agentId || !sessionId || activeSessionRef.current !== session) return;+ const snapshotVersion = snapshotVersionRef.current;+ try {+ const response = await chatApi.deleteQueued(itemId, agentId, sessionId);+ applyMutationSnapshot(response.items, snapshotVersion);+ } catch (error) {+ if (activeSessionRef.current === session) onError(error as Error);+ throw error;+ }+ },+ [agentId, sessionId, session, applyMutationSnapshot, onError],+ );++ const reorderQueued = useCallback(+ async (visibleItemIds: string[]) => {+ if (!agentId || !sessionId || activeSessionRef.current !== session) return;+ const current = itemsRef.current;+ if (current.some((item) => item.id.startsWith(OPTIMISTIC_ITEM_PREFIX))) return;++ const visibleIds = current+ .filter(+ (item) =>+ !getQueueMessages([item]).some((message) =>+ conversationMessageIdsRef.current.has(message.id),+ ),+ )+ .map((item) => item.id);+ const visibleIdSet = new Set(visibleIds);+ if (+ visibleItemIds.length !== visibleIds.length ||+ new Set(visibleItemIds).size !== visibleIds.length ||+ visibleItemIds.some((itemId) => !visibleIdSet.has(itemId))+ ) {+ return;+ }++ let visibleIndex = 0;+ const fullItemIds = current.map((item) =>+ visibleIdSet.has(item.id) ? visibleItemIds[visibleIndex++] : item.id,+ );+ const snapshotVersion = snapshotVersionRef.current;+ try {+ const response = await chatApi.reorderQueued(agentId, sessionId, fullItemIds);+ applyMutationSnapshot(response.items, snapshotVersion);+ } catch (error) {+ if (activeSessionRef.current === session) {+ onError(error as Error);+ if (error instanceof ApiError && error.status === 409) {+ await refreshQueue();+ }+ }+ throw error;+ }+ },+ [agentId, sessionId, session, applyMutationSnapshot, onError, refreshQueue],+ );++ const moveQueued = useCallback(+ async (itemId: string, direction: -1 | 1) => {+ const current = itemsRef.current.filter(+ (item) =>+ !getQueueMessages([item]).some((message) =>+ conversationMessageIdsRef.current.has(message.id),+ ),+ );+ const index = current.findIndex((item) => item.id === itemId);+ const nextIndex = index + direction;+ if (index < 0 || nextIndex < 0 || nextIndex >= current.length) return;+ const reordered = [...current];+ [reordered[index], reordered[nextIndex]] = [reordered[nextIndex], reordered[index]];+ await reorderQueued(reordered.map((item) => item.id));+ },+ [reorderQueued],+ );++ const visibleItems = useMemo(+ () =>+ items.filter(+ (item) =>+ !getQueueMessages([item]).some((message) =>+ conversationMessageIds.has(message.id),+ ),+ ),+ [conversationMessageIds, items],+ );+ const reorderDisabled = useMemo(+ () => items.some((item) => item.id.startsWith(OPTIMISTIC_ITEM_PREFIX)),+ [items],+ );++ return {+ items: visibleItems,+ visibleCount: visibleItems.length,+ pendingCount: items.length,+ reorderDisabled,+ addOptimistic,+ acceptOptimistic,+ rollbackOptimistic,+ applyQueueSnapshot,+ startItem,+ finishItem,+ updateQueued,+ deleteQueued,+ moveQueued,+ reorderQueued,+ };+}diff --git a/examples/web_ui/frontend/src/hooks/useMessages.ts b/examples/web_ui/frontend/src/hooks/useMessages.tsindex 17c0672ff..a4bc4564f 100644--- a/examples/web_ui/frontend/src/hooks/useMessages.ts+++ b/examples/web_ui/frontend/src/hooks/useMessages.ts@@ -11,12 +11,18 @@ import type {import { appendEvent, AssistantMsg, UserMsg } from '@agentscope-ai/agentscope/message';import type { Msg, ContentBlock } from '@agentscope-ai/agentscope/message';import type { ToolCallBlock } from '@agentscope-ai/agentscope/message';-import { useState, useCallback, useRef, useEffect } from 'react';+import { useState, useCallback, useRef, useEffect, useMemo, useLayoutEffect } from 'react';import { toast } from 'sonner';-import { sessionApi, takeFreshlyCreated } from '@/api';-import { chatApi } from '@/api';+import { chatApi, sessionApi, takeFreshlyCreated } from '@/api';+import type { ChatQueueItem } from '@/api/chat';import { useAudioManager } from '@/context/AudioContext';+import {+ getQueueMessages,+ type ChatInputStartedValue,+ type ChatInputTerminalValue,+ useChatQueue,+} from '@/hooks/useChatQueue';import { useTranslation } from '@/i18n/useI18n';/**@@ -62,9 +68,10 @@ const hitlKey = (e: { worker_session_id: string; reply_id: string }) =>** - ``idle`` — no in-flight reply; the send button is enabled.* - ``streaming`` — a reply is in progress (either actively producing- * events or parked awaiting HITL). The send button is replaced by a- * Stop button. The parked-vs-generating distinction is not tracked- * here; HITL cards render themselves from message content when a+ * events or parked awaiting HITL). A separate Stop button is shown,+ * while Send remains available to enqueue another turn. The+ * parked-vs-generating distinction is not tracked here; HITL cards+ * render themselves from message content when a* ``RequireUserConfirmEvent`` block is present.* - ``interrupting`` — the user has requested a stop and we are* waiting for the backend's terminating ``ReplyEndEvent``. Stop@@ -90,10 +97,10 @@ const INTERRUPT_TIMEOUT_MS = 10_000;* background retrigger, team member message, …).** The hook opens the SSE connection immediately after fetching- * history. User input is sent via ``POST /chat/``. Human-in-the-loop- * confirmations use the active realtime control channel during voice- * mode and ``POST /chat/`` otherwise. Resulting events arrive through- * the already-open SSE connection.+ * history. Ordinary user input is accepted into the backend FIFO.+ * Human-in-the-loop confirmations use the active realtime control+ * channel during voice mode and ``POST /chat/`` otherwise. Resulting+ * events arrive through the already-open SSE connection.** ``phase`` is driven by event content, not HTTP lifecycle: it moves* to ``streaming`` on ``ReplyStartEvent`` and back to ``idle`` on@@ -104,10 +111,9 @@ const INTERRUPT_TIMEOUT_MS = 10_000;* @param agentId - The agent whose session to subscribe. ``null`` to* skip.* @param sessionId - The session to subscribe. ``null`` to skip.- * @returns Object with ``msgs``, ``loading``, ``phase``, ``error``,- * ``send``, ``onUserConfirm``, and ``abort``. ``loading`` stays true- * until the history for the *current* ``(agentId, sessionId)`` has- * landed, so ``msgs`` must not be rendered while it is set.+ * @returns Message/reply state, editable queue state and mutations, HITL+ * handlers, send/interrupt actions, loading state, and the latest error.+ * ``loading`` stays true until history for the current session lands.*/export function useMessages(agentId: string | null,@@ -141,6 +147,15 @@ export function useMessages(},) {const { t } = useTranslation();+ // A new identity for each visit also rejects late responses after A -> B -> A.+ const session = useMemo(() => ({ agentId, sessionId }), [agentId, sessionId]);+ const activeSessionRef = useRef<typeof session | null>(null);+ useLayoutEffect(() => {+ activeSessionRef.current = session;+ return () => {+ activeSessionRef.current = null;+ };+ }, [session]);const [msgs, setMsgs] = useState<Msg[]>([]);// The (agent, session) pair `msgs` actually belongs to. Loading is// derived from it rather than set inside the fetch effect: an effect@@ -152,6 +167,22 @@ export function useMessages(const [error, setError] = useState<Error | null>(null);// Pending subagent HITL cards projected onto this (leader) session.const [subagentHitl, setSubagentHitl] = useState<SubagentHitlEntry[]>([]);+ const {+ items: queuedItems,+ visibleCount: queuedCount,+ pendingCount: pendingQueueCount,+ reorderDisabled: queueReorderDisabled,+ addOptimistic,+ acceptOptimistic,+ rollbackOptimistic,+ applyQueueSnapshot,+ startItem,+ finishItem,+ updateQueued,+ deleteQueued,+ moveQueued,+ reorderQueued,+ } = useChatQueue(agentId, sessionId, setError);const msgsRef = useRef<Msg[]>([]);const currentReplyRef = useRef<Msg | null>(null);@@ -219,6 +250,38 @@ export function useMessages(// 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)));+ } else if (custom.name === 'chat_input_started') {+ const startedItem = startItem(custom.value as ChatInputStartedValue);+ if (startedItem) {+ const existingIds = new Set(msgsRef.current.map((msg) => msg.id));+ msgsRef.current = [+ ...msgsRef.current,+ ...getQueueMessages([startedItem]).filter(+ (msg) => !existingIds.has(msg.id),+ ),+ ];+ scheduleUpdate();+ }+ } else if (custom.name === 'chat_queue_changed') {+ const value = custom.value as { items?: ChatQueueItem[] };+ applyQueueSnapshot(value.items ?? []);+ } else if (custom.name === 'chat_input_failed') {+ const value = custom.value as ChatInputTerminalValue;+ finishItem(value);+ const failure = new Error(value.message ?? t('chatQueue.processFailed'));+ clearInterruptTimer();+ currentReplyRef.current = null;+ setPhase('idle');+ setError(failure);+ toast.error(failure.message);+ } else if (custom.name === 'chat_input_cancelled') {+ const value = custom.value as ChatInputTerminalValue;+ finishItem(value);+ const message = value.message ?? t('chatQueue.processingCancelled');+ clearInterruptTimer();+ currentReplyRef.current = null;+ setPhase('idle');+ toast.info(message);}return;}@@ -308,7 +371,17 @@ export function useMessages(scheduleUpdate();},- [scheduleUpdate, audioManager, clearInterruptTimer, t, agentId, sessionId],+ [+ scheduleUpdate,+ audioManager,+ clearInterruptTimer,+ startItem,+ applyQueueSnapshot,+ finishItem,+ t,+ agentId,+ sessionId,+ ],);// ── Lifecycle: fetch history + open SSE stream ──────────────────@@ -408,31 +481,55 @@ export function useMessages(}, [agentId, sessionId, scheduleUpdate, processEvent, audioManager, clearInterruptTimer]);/**- * Send a user message. Appends the message to the local list- * optimistically, then fires a ``POST /chat/`` trigger. Events- * arrive via the already-open SSE connection.+ * Send a user message. The first idle input appears in the conversation+ * immediately (with its matching queue row hidden); later inputs remain+ * in the editable queue until ``chat_input_started`` arrives.** @param content - The message content blocks.*/const send = useCallback(async (content: ContentBlock[]) => {- if (!agentId || !sessionId) return;+ if (!agentId || !sessionId || activeSessionRef.current !== session) return;const userMsg = UserMsg({ name: 'user', content });- msgsRef.current = [...msgsRef.current, userMsg];- scheduleUpdate();-+ const showInConversationImmediately = phase === 'idle' && pendingQueueCount === 0;+ if (showInConversationImmediately) {+ msgsRef.current = [...msgsRef.current, userMsg];+ scheduleUpdate();+ }+ const optimisticId = addOptimistic(userMsg, showInConversationImmediately);try {- await chatApi.trigger({+ const response = await chatApi.trigger({agent_id: agentId,session_id: sessionId,input: userMsg,});+ if (activeSessionRef.current !== session) return;+ acceptOptimistic(optimisticId, response.queue_item_id);} catch (e) {+ if (activeSessionRef.current !== session) return;+ // The server never accepted this input. Remove the+ // optimistic queue row and restore the caller's draft.+ rollbackOptimistic(optimisticId, userMsg.id);+ if (showInConversationImmediately) {+ msgsRef.current = msgsRef.current.filter((msg) => msg.id !== userMsg.id);+ scheduleUpdate();+ }setError(e as Error);+ throw e;}},- [agentId, sessionId, scheduleUpdate],+ [+ agentId,+ sessionId,+ phase,+ pendingQueueCount,+ session,+ scheduleUpdate,+ addOptimistic,+ acceptOptimistic,+ rollbackOptimistic,+ ],);/**@@ -606,6 +703,13 @@ export function useMessages(return {msgs: ownsConversation ? msgs : [],loading,+ queuedItems: ownsConversation ? queuedItems : [],+ queuedCount: ownsConversation ? queuedCount : 0,+ queueReorderDisabled: !ownsConversation || queueReorderDisabled,+ updateQueued,+ deleteQueued,+ moveQueued,+ reorderQueued,phase: ownsConversation ? phase : ('idle' as ReplyPhase),error: ownsConversation ? error : null,send,diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.jsonindex 9b2fd6af7..cd7e7ce6a 100644--- a/examples/web_ui/frontend/src/i18n/locales/en.json+++ b/examples/web_ui/frontend/src/i18n/locales/en.json@@ -100,8 +100,25 @@"attach": "Attach file","attachNotSupported": "This model does not support file attachments","send": "Send",- "stop": "Stop generating",- "stopping": "Stopping ..."+ "queue": "Add to queue",+ "queued_one": "{{count}} message queued",+ "queued_other": "{{count}} messages queued",+ "stop": "Stop current reply",+ "stopping": "Stopping current reply ..."+ },+ "chatQueue": {+ "title_one": "Pending message ({{count}})",+ "title_other": "Pending messages ({{count}})",+ "attachmentOnly": "Attachment message",+ "drag": "Drag to reorder",+ "moveUp": "Move up",+ "moveDown": "Move down",+ "edit": "Edit",+ "delete": "Delete",+ "save": "Save",+ "cancel": "Cancel",+ "processFailed": "The queued message could not be processed.",+ "processingCancelled": "Queued message processing was interrupted."},"confirmCard": {"toConfirm": "to confirm",diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.jsonindex 11df20889..6d25c0263 100644--- a/examples/web_ui/frontend/src/i18n/locales/zh.json+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json@@ -100,8 +100,25 @@"attach": "添加附件","attachNotSupported": "当前模型不支持文件附件","send": "发送",- "stop": "停止生成",- "stopping": "停止中 ..."+ "queue": "加入队列",+ "queued_one": "{{count}} 条消息正在排队",+ "queued_other": "{{count}} 条消息正在排队",+ "stop": "停止当前回复",+ "stopping": "正在停止当前回复 ..."+ },+ "chatQueue": {+ "title_one": "待发送消息({{count}} 条)",+ "title_other": "待发送消息({{count}} 条)",+ "attachmentOnly": "附件消息",+ "drag": "拖动调整顺序",+ "moveUp": "上移",+ "moveDown": "下移",+ "edit": "编辑",+ "delete": "删除",+ "save": "保存",+ "cancel": "取消",+ "processFailed": "排队消息处理失败。",+ "processingCancelled": "排队消息处理已中断。"},"confirmCard": {"toConfirm": "确认",diff --git a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsxindex 3fae74978..0ae50a4ee 100644--- a/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx+++ b/examples/web_ui/frontend/src/pages/chat/ChatViewport.tsx@@ -264,7 +264,14 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatViewmsgs,loading: messagesLoading,phase,+ queuedCount,+ queuedItems,+ queueReorderDisabled,send,+ updateQueued,+ deleteQueued,+ moveQueued,+ reorderQueued,onUserConfirm,onSubagentConfirm,subagentHitl,@@ -917,20 +924,20 @@ export function ChatViewport({ agentId, sessionId, onSessionsChanged }: ChatViewgit={workspaceStatus?.git ?? null}onRefreshGit={refetchWorkspaceStatus}phase={phase}+ queuedCount={queuedCount}+ queuedItems={queuedItems}+ queueReorderDisabled={queueReorderDisabled}disabled={selectedModel === null || voiceBusy}onSend={send}onUserConfirm={onUserConfirm}onInterrupt={interrupt}+ onUpdateQueued={updateQueued}+ onDeleteQueued={deleteQueued}+ onMoveQueued={moveQueued}+ onReorderQueued={reorderQueued}voiceState={realtimeVoice.state}onVoiceToggle={() => void realtimeVoice.toggle()}voiceDisabled={!selectedRealtimeModel || !agentId || !sessionId}- // cwd={- // {cwd: view?.session.config.cwd, git: {- // branch: 'main',- // deletion: 0,- // addition: 0,- // }}- // }footerSlot={subagentHitl.length > 0 ? (<SubagentHitlCarddiff --git a/src/agentscope/app/_bus_ops.py b/src/agentscope/app/_bus_ops.pyindex eb7f1e23e..57eeea681 100644--- a/src/agentscope/app/_bus_ops.py+++ b/src/agentscope/app/_bus_ops.py@@ -14,14 +14,28 @@ other's internals.- Append an event to the session replay log and fan it out live.* - :func:`enqueue_run_trigger`- Enqueue a typed run trigger and signal dispatchers.+ * - :func:`enqueue_chat_input`+ - Append an ordinary user turn to a per-session FIFO.* - :func:`enqueue_index_task`- Enqueue a knowledge-document indexing task and signal consumers."""from __future__ import annotations-from typing import TYPE_CHECKING, Literal+import json+import uuid+from contextlib import AsyncExitStack, asynccontextmanager+from datetime import datetime, timezone+from typing import AsyncGenerator, TYPE_CHECKING, Literal+from .._logging import logger+from ..event import CustomEventfrom .message_bus._keys import MessageBusKeys+from ._chat_input_store import (+ cleanup_session,+ discard_input,+ decode_input,+ queue_entry,+)if TYPE_CHECKING:from .message_bus._base import MessageBus@@ -37,6 +51,126 @@ if TYPE_CHECKING:# ── publish_session_event ──────────────────────────────────────────────+class ChatQueueFullError(RuntimeError):+ """Raised when a session has reached its pending-turn limit."""+++class ChatQueueBusyError(RuntimeError):+ """Raised when a short queue mutation lock cannot be acquired."""+++@asynccontextmanager+async def chat_input_mutation(+ bus: "MessageBus",+ session_id: str,+ *,+ timeout_secs: float | None = None,+) -> AsyncGenerator[None, None]:+ """Acquire a short-lived queue mutation lock with bounded waiting.++ Args:+ bus (`MessageBus`):+ Application message bus that owns the distributed lock.+ session_id (`str`):+ Session whose pending-input queue will be mutated.+ timeout_secs (`float | None`, optional):+ Maximum time to wait for the lock. ``None`` uses the configured+ queue-mutation timeout.++ Yields:+ `None`:+ Control while the session mutation lock is held.++ Raises:+ `ChatQueueBusyError`:+ The lock could not be acquired before the timeout.+ """+ timeout = (+ MessageBusKeys.CHAT_INPUT_MUTATION_TIMEOUT_SECS+ if timeout_secs is None+ else timeout_secs+ )+ async with AsyncExitStack() as stack:+ try:+ await stack.enter_async_context(+ bus.acquire_lock_bounded(+ MessageBusKeys.chat_input_mutation_lock(session_id),+ ttl_secs=MessageBusKeys.CHAT_INPUT_MUTATION_TTL_SECS,+ timeout_secs=timeout,+ ),+ )+ except TimeoutError as exc:+ raise ChatQueueBusyError(+ "The pending message queue is busy; retry shortly.",+ ) from exc+ yield+++@asynccontextmanager+async def _chat_input_user_quota(+ bus: "MessageBus",+ user_id: str,+) -> AsyncGenerator[None, None]:+ """Serialize the bounded per-user quota check performed by enqueue.++ Args:+ bus (`MessageBus`):+ Application message bus that owns the distributed lock.+ user_id (`str`):+ User whose aggregate pending-input quota is being checked.++ Yields:+ `None`:+ Control while the per-user quota lock is held.++ Raises:+ `ChatQueueBusyError`:+ The quota lock could not be acquired before the timeout.+ """+ async with AsyncExitStack() as stack:+ try:+ await stack.enter_async_context(+ bus.acquire_lock_bounded(+ MessageBusKeys.chat_input_user_quota_lock(user_id),+ ttl_secs=MessageBusKeys.CHAT_INPUT_MUTATION_TTL_SECS,+ timeout_secs=(+ MessageBusKeys.CHAT_INPUT_MUTATION_TIMEOUT_SECS+ ),+ ),+ )+ except TimeoutError as exc:+ raise ChatQueueBusyError(+ "The pending message quota is busy; retry shortly.",+ ) from exc+ yield+++def _serialized_input(+ inputs: "Msg | list[Msg]",+) -> dict | list[dict]:+ """Serialize one ordinary input without imposing a queue byte limit.++ Args:+ inputs (`Msg | list[Msg]`):+ One message or a non-empty ordered message list.++ Returns:+ `dict | list[dict]`:+ JSON-compatible message payload suitable for the bus.++ Raises:+ `ValueError`:+ ``inputs`` is an empty list.+ """+ if isinstance(inputs, list) and not inputs:+ raise ValueError("A queued message list must not be empty.")+ return (+ [msg.model_dump(mode="json") for msg in inputs]+ if isinstance(inputs, list)+ else inputs.model_dump(mode="json")+ )++async def publish_session_event(bus: "MessageBus",session_id: str,@@ -79,14 +213,16 @@ async def enqueue_run_trigger("wake","resume","message",+ "queued_message",] = MessageBusKeys.WAKEUP_KIND_WAKE,inputs: UserConfirmResultEvent| ExternalExecutionResultEvent| UserInterruptEvent| Msg| None = None,+ signal: bool = True,) -> None:- """Enqueue a typed run trigger and signal dispatchers.+ """Enqueue a typed run trigger and optionally signal dispatchers.``kind`` selects how the dispatcher handles the entry:@@ -101,6 +237,8 @@ async def enqueue_run_trigger(inbound channel message). Like ``resume`` it carries input and isre-queued rather than dropped while the session is running; the runpersists it and reasons over it as a real user turn.+ - ``queued_message`` — signal that a session's ordinary browser-input+ FIFO should be drained. ``inputs`` must be ``None``.The payload is serialised to a plain dict before being pushed to thewakeup queue; the ``MessageBus`` transport layer never sees event@@ -118,10 +256,14 @@ async def enqueue_run_trigger(kind:Trigger kind. Defaults to ``"wake"``.inputs:- The input event for ``resume`` triggers. Ignored (and- should be ``None``) for ``wake``. The function calls- ``model_dump(mode="json")`` internally — callers pass the- event object, not a pre-serialised dict.+ The input for ``resume`` and ``message`` triggers. Ignored (and+ should be ``None``) for ``wake`` and ``queued_message``. The+ function calls ``model_dump(mode="json")`` internally — callers+ pass the model object, not a pre-serialised dict.+ signal:+ Whether to publish the shared wakeup signal after pushing.+ Recovery sweeps pass ``False`` to batch many durable triggers+ behind one signal."""await bus.queue_push(MessageBusKeys.wakeup_queue(),@@ -133,7 +275,599 @@ async def enqueue_run_trigger("input": inputs.model_dump(mode="json") if inputs else None,},)- await bus.publish(MessageBusKeys.wakeup_signal(), {})+ if signal:+ await bus.publish(MessageBusKeys.wakeup_signal(), {})+++async def nudge_chat_inputs(+ bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+) -> None:+ """Wake pending input after releasing a run lock; recovery is fallback."""+ try:+ pending = await bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ )+ claimed = await bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ if pending or claimed:+ await enqueue_run_trigger(+ bus,+ user_id,+ session_id,+ agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )+ except Exception:+ logger.exception("Failed to nudge queued inputs for %s.", session_id)+++async def enqueue_chat_input(+ bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ inputs: Msg | list[Msg],+) -> dict:+ """Append an ordinary user turn to a session FIFO and wake its pump.++ The input and its wake-up marker are deliberately separate: the+ per-session queue owns ordering, while the shared trigger queue only+ nudges an available dispatcher. Duplicate ``queued_message`` triggers+ are harmless because the per-session queue is consumed exactly once.+ Once the input is stored, notification failures are logged rather than+ reported as rejection; pending-input recovery retries dispatch.++ Args:+ bus:+ Application message bus.+ user_id:+ Owning user id.+ session_id:+ Target session id.+ agent_id:+ Agent that owns the session.+ inputs:+ One user message or a non-empty ordered message list.++ Returns:+ `dict`:+ Public queue item containing ``id``, ``created_at``, and+ serialized ``input``.++ Raises:+ `ValueError`:+ ``inputs`` is an empty list.+ `ChatQueueFullError`:+ The session queue or aggregate per-user quota is full.+ `ChatQueueBusyError`:+ A queue or quota mutation lock cannot be acquired promptly.+ """+ serialized = _serialized_input(inputs)+ item: dict = {+ # Queue identity is independent from message identity. Clients may+ # legitimately retry/replay the same Msg.id; management operations+ # still need one unambiguous id per pending turn.+ "id": uuid.uuid4().hex,+ "user_id": user_id,+ "session_id": session_id,+ "agent_id": agent_id,+ "created_at": datetime.now(timezone.utc).isoformat(),+ "input": serialized,+ }+ async with _chat_input_user_quota(bus, user_id):+ if (+ await _count_user_chat_inputs(bus, user_id)+ >= MessageBusKeys.CHAT_INPUT_USER_MAX_LEN+ ):+ raise ChatQueueFullError(+ "Your pending message quota is full; wait for a message "+ "to finish or remove one before sending another.",+ )+ async with chat_input_mutation(bus, session_id):+ existing = await bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=MessageBusKeys.CHAT_INPUT_MAX_LEN,+ )+ if len(existing) >= MessageBusKeys.CHAT_INPUT_MAX_LEN:+ raise ChatQueueFullError(+ "The pending message queue is full; wait for a message "+ "to start or remove one before sending another.",+ )+ # Register before pushing. If the process dies between these two+ # operations recovery sees a harmless stale marker and removes it;+ # the inverse order could leave an unindexed queue permanently+ # stranded after a lost trigger.+ await bus.registry_set(+ MessageBusKeys.chat_input_pending_registry(),+ session_id,+ json.dumps(+ {+ "user_id": user_id,+ "agent_id": agent_id,+ },+ ),+ )+ await bus.registry_set(+ MessageBusKeys.chat_input_user_sessions(user_id),+ session_id,+ agent_id,+ )+ item["input_ref"] = item["id"]+ await bus.registry_set(+ MessageBusKeys.chat_input_payloads(session_id),+ item["input_ref"],+ json.dumps(serialized),+ )+ await bus.queue_push(+ MessageBusKeys.chat_inputs(session_id),+ queue_entry(item),+ )+ try:+ await _publish_chat_queue_changed(bus, session_id)+ except Exception:+ logger.exception(+ "Chat input %s accepted, but queue notification failed.",+ item["id"],+ )+ try:+ await enqueue_run_trigger(+ bus,+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )+ except Exception:+ logger.exception(+ "Chat input %s accepted; wakeup failed, awaiting recovery.",+ item["id"],+ )+ return _public_chat_input(item)+++async def list_chat_inputs(+ bus: "MessageBus",+ session_id: str,+) -> list[dict]:+ """Return editable pending turns for a session in FIFO order.++ Args:+ bus (`MessageBus`):+ Application message bus.+ session_id (`str`):+ Session whose pending queue should be inspected.++ Returns:+ `list[dict]`:+ Public queue items ordered from the next turn to the last.+ """+ payloads = await _read_chat_input_payloads(bus, session_id)+ return [_public_chat_input(payload) for payload in payloads]+++async def update_chat_input(+ bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ item_id: str,+ inputs: Msg | list[Msg],+) -> list[dict]:+ """Replace one still-pending turn and return the updated queue.++ Args:+ bus (`MessageBus`):+ Application message bus.+ user_id (`str`):+ User that must own the pending item.+ session_id (`str`):+ Session that owns the pending queue.+ agent_id (`str`):+ Agent that must own the pending item.+ item_id (`str`):+ Stable business id of the item to update.+ inputs (`Msg | list[Msg]`):+ Replacement message or non-empty ordered message list.++ Returns:+ `list[dict]`:+ Complete public queue snapshot after the update.++ Raises:+ `ValueError`:+ ``inputs`` is an empty list.+ `LookupError`:+ The item is no longer pending or is not owned by the caller.+ `ChatQueueBusyError`:+ The session mutation lock cannot be acquired promptly.+ """+ serialized = _serialized_input(inputs)+ async with chat_input_mutation(bus, session_id):+ payloads = await _read_chat_input_payloads(bus, session_id)+ item = _owned_chat_input(+ payloads,+ user_id,+ session_id,+ agent_id,+ item_id,+ )+ previous = dict(item)+ item["input"] = serialized+ item["input_ref"] = uuid.uuid4().hex+ await bus.registry_set(+ MessageBusKeys.chat_input_payloads(session_id),+ item["input_ref"],+ json.dumps(serialized),+ )+ await bus.queue_replace(+ MessageBusKeys.chat_inputs(session_id),+ [queue_entry(payload) for payload in payloads],+ )+ await discard_input(bus, previous)+ return await _notify_chat_queue_changed(bus, session_id, payloads)+++async def delete_chat_input(+ bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ item_id: str,+) -> list[dict]:+ """Delete one still-pending turn and return the updated queue.++ Args:+ bus (`MessageBus`):+ Application message bus.+ user_id (`str`):+ User that must own the pending item.+ session_id (`str`):+ Session that owns the pending queue.+ agent_id (`str`):+ Agent that must own the pending item.+ item_id (`str`):+ Stable business id of the item to delete.++ Returns:+ `list[dict]`:+ Complete public queue snapshot after deletion.++ Raises:+ `LookupError`:+ The item is no longer pending or is not owned by the caller.+ `ChatQueueBusyError`:+ The session mutation lock cannot be acquired promptly.+ """+ async with chat_input_mutation(bus, session_id):+ payloads = await _read_chat_input_payloads(bus, session_id)+ item = _owned_chat_input(+ payloads,+ user_id,+ session_id,+ agent_id,+ item_id,+ )+ payloads.remove(item)+ await bus.queue_replace(+ MessageBusKeys.chat_inputs(session_id),+ [queue_entry(payload) for payload in payloads],+ )+ await discard_input(bus, item)+ return await _notify_chat_queue_changed(bus, session_id, payloads)+++async def reorder_chat_inputs(+ bus: "MessageBus",+ user_id: str,+ session_id: str,+ agent_id: str,+ item_ids: list[str],+) -> list[dict]:+ """Atomically replace the pending queue order.++ ``item_ids`` must be an exact permutation of the queue snapshot. If a+ turn started or another client changed the queue in the meantime the+ operation fails instead of silently dropping or duplicating an item.++ Args:+ bus (`MessageBus`):+ Application message bus.+ user_id (`str`):+ User whose owned items may be reordered.+ session_id (`str`):+ Session that owns the pending queue.+ agent_id (`str`):+ Agent whose owned items may be reordered.+ item_ids (`list[str]`):+ Exact desired permutation of the caller-owned pending item ids.++ Returns:+ `list[dict]`:+ Complete public queue snapshot after reordering.++ Raises:+ `ValueError`:+ The supplied ids contain duplicates or are not an exact+ permutation of the current owned snapshot.+ `ChatQueueBusyError`:+ The session mutation lock cannot be acquired promptly.+ """+ async with chat_input_mutation(bus, session_id):+ payloads = await _read_chat_input_payloads(bus, session_id)+ owned = [+ payload+ for payload in payloads+ if payload.get("user_id") == user_id+ and payload.get("session_id") == session_id+ and payload.get("agent_id") == agent_id+ ]+ current_ids = [str(payload.get("id")) for payload in owned]+ if (+ len(item_ids) != len(set(item_ids))+ or set(item_ids) != set(current_ids)+ or len(item_ids) != len(current_ids)+ ):+ raise ValueError(+ "The pending queue changed; refresh it before reordering.",+ )+ by_id = {str(payload["id"]): payload for payload in owned}+ reordered_owned = iter(by_id[item_id] for item_id in item_ids)+ # Preserve payloads outside this caller's ownership at their exact+ # positions. They indicate corrupt/legacy state, but a defensive+ # reorder must never erase them.+ reordered = [+ next(reordered_owned)+ if (+ payload.get("user_id") == user_id+ and payload.get("session_id") == session_id+ and payload.get("agent_id") == agent_id+ )+ else payload+ for payload in payloads+ ]+ await bus.queue_replace(+ MessageBusKeys.chat_inputs(session_id),+ [queue_entry(payload) for payload in reordered],+ )+ return await _notify_chat_queue_changed(+ bus,+ session_id,+ reordered,+ )+++async def _read_chat_input_payloads(+ bus: "MessageBus",+ session_id: str,+) -> list[dict]:+ """Hydrate editable entries, omitting claims and deleted references.++ Args:+ bus (`MessageBus`):+ Application message bus.+ session_id (`str`):+ Session whose raw queue payloads should be read.++ Returns:+ `list[dict]`:+ Raw oldest-first queue payloads, including routing metadata.+ """+ entries = await bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=MessageBusKeys.CHAT_INPUT_MAX_LEN,+ )+ # A failed dequeue can leave a durable claim in the physical FIFO.+ # Mutations call this reader under the same lock as claim creation;+ # they must never replace or discard the claimed input reference.+ raw_claim = await bus.registry_get(+ MessageBusKeys.chat_input_claim(session_id),+ "claim",+ )+ if raw_claim is not None:+ try:+ claimed_id = json.loads(raw_claim)["payload"]["id"]+ except (KeyError, TypeError, ValueError):+ logger.warning("Invalid chat-input claim for %s.", session_id)+ else:+ entries = [+ entry for entry in entries if entry[1].get("id") != claimed_id+ ]+ refs = [+ entry["input_ref"]+ for _, entry in entries+ if "input" not in entry and isinstance(entry.get("input_ref"), str)+ ]+ values = (+ await bus.registry_get_many(+ MessageBusKeys.chat_input_payloads(session_id),+ refs,+ )+ if refs+ else []+ )+ inputs = dict(zip(refs, values))+ payloads = []+ for _entry_id, entry in entries:+ payload = (+ entry+ if "input" in entry+ else decode_input(+ entry,+ inputs.get(entry.get("input_ref")),+ )+ )+ if payload is not None:+ payloads.append(payload)+ return payloads+++async def _count_user_chat_inputs(+ bus: "MessageBus",+ user_id: str,+) -> int:+ """Count one user's pending and claimed turns across all sessions.++ Args:+ bus (`MessageBus`):+ Application message bus.+ user_id (`str`):+ User whose aggregate queue usage should be counted.++ Returns:+ `int`:+ Pending and distinct in-flight turns, capped once the configured+ per-user quota is reached.+ """+ sessions = await bus.registry_getall(+ MessageBusKeys.chat_input_user_sessions(user_id),+ )+ count = 0+ for session_id in sessions:+ entries = await bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=MessageBusKeys.CHAT_INPUT_MAX_LEN,+ )+ ids = {payload["id"] for _, payload in entries}+ raw = await bus.registry_get(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ if raw is not None:+ try:+ item_id = json.loads(raw)["id"]+ if not isinstance(item_id, str) or not item_id:+ raise ValueError("Invalid claimed item id.")+ except (KeyError, TypeError, ValueError):+ logger.warning(+ "Invalid quota claim for session %s; counting one item.",+ session_id,+ )+ count += 1+ else:+ ids.add(item_id)+ count += len(ids)+ if count >= MessageBusKeys.CHAT_INPUT_USER_MAX_LEN:+ return count+ return count+++def _owned_chat_input(+ payloads: list[dict],+ user_id: str,+ session_id: str,+ agent_id: str,+ item_id: str,+) -> dict:+ """Resolve an owned pending item or report that it already started.++ Args:+ payloads (`list[dict]`):+ Raw pending queue snapshot.+ user_id (`str`):+ User that must own the item.+ session_id (`str`):+ Session that must own the item.+ agent_id (`str`):+ Agent that must own the item.+ item_id (`str`):+ Stable business id to resolve.++ Returns:+ `dict`:+ Matching mutable raw payload from ``payloads``.++ Raises:+ `LookupError`:+ No matching, caller-owned pending item exists.+ """+ for payload in payloads:+ if (+ payload.get("id") == item_id+ and payload.get("user_id") == user_id+ and payload.get("session_id") == session_id+ and payload.get("agent_id") == agent_id+ ):+ return payload+ raise LookupError(+ f"Queued message '{item_id}' is no longer pending.",+ )+++def _public_chat_input(payload: dict) -> dict:+ """Strip routing metadata from one queue item returned to clients.++ Args:+ payload (`dict`):+ Raw queue payload containing identity, routing, and input data.++ Returns:+ `dict`:+ Client-safe ``id``, ``created_at``, and ``input`` fields.+ """+ return {+ "id": payload["id"],+ "created_at": payload["created_at"],+ "input": payload["input"],+ }+++async def _publish_chat_queue_changed(+ bus: "MessageBus",+ session_id: str,+ payloads: list[dict] | None = None,+) -> list[dict]:+ """Publish a complete queue snapshot and return its public items.++ Args:+ bus (`MessageBus`):+ Application message bus used for the live fan-out.+ session_id (`str`):+ Session whose subscribers receive the snapshot.+ payloads (`list[dict] | None`, optional):+ Raw snapshot to publish. ``None`` reads the current queue and+ therefore requires the caller to hold the mutation lock.++ Returns:+ `list[dict]`:+ Public queue items included in the live event.+ """+ if payloads is None:+ payloads = await _read_chat_input_payloads(bus, session_id)+ if not payloads:+ await cleanup_session(bus, session_id)+ items = [_public_chat_input(payload) for payload in payloads]+ event = CustomEvent(name="chat_queue_changed", value={"items": items})+ # Queue state is an ephemeral projection backed by GET /chat/queue.+ # Publishing it live avoids O(n²) replay-log growth and stale snapshots+ # temporarily rolling the UI backwards after an SSE reconnect.+ await bus.publish(+ MessageBusKeys.session_events(session_id),+ event.model_dump(mode="json"),+ )+ return items+++async def _notify_chat_queue_changed(+ bus: "MessageBus",+ session_id: str,+ payloads: list[dict],+) -> list[dict]:+ """Return committed state even when its live notification fails."""+ items = [_public_chat_input(payload) for payload in payloads]+ try:+ await _publish_chat_queue_changed(bus, session_id, payloads)+ except Exception:+ logger.exception(+ "Queue mutation committed; notification failed for %s.",+ session_id,+ )+ return items# ── session inbox hand-off ─────────────────────────────────────────────diff --git a/src/agentscope/app/_chat_input_store.py b/src/agentscope/app/_chat_input_store.pynew file mode 100644index 000000000..315f19d6b--- /dev/null+++ b/src/agentscope/app/_chat_input_store.py@@ -0,0 +1,92 @@+# -*- coding: utf-8 -*-+"""Session-local payload storage and lightweight queue indexes."""+import json+from typing import TYPE_CHECKING++from .._logging import logger+from .message_bus import MessageBusKeys++if TYPE_CHECKING:+ from .message_bus import MessageBus+++def queue_entry(payload: dict) -> dict:+ """Remove hydrated input from a reference-backed queue entry."""+ if "input_ref" not in payload:+ return payload+ return {key: value for key, value in payload.items() if key != "input"}+++async def hydrate_input(bus: "MessageBus", payload: dict) -> dict | None:+ """Load one input reference; tolerate a concurrently deleted item."""+ if "input" in payload:+ return payload+ if "input_ref" not in payload:+ return None+ raw = await bus.registry_get(+ MessageBusKeys.chat_input_payloads(payload["session_id"]),+ payload["input_ref"],+ )+ if raw is None:+ return None+ return decode_input(payload, raw)+++def decode_input(payload: dict, raw: str | None) -> dict | None:+ """Decode a referenced input, omitting missing or corrupt payloads."""+ if raw is None:+ return None+ try:+ return {**payload, "input": json.loads(raw)}+ except (TypeError, ValueError):+ logger.warning("Invalid queued input payload %s.", payload.get("id"))+ return None+++async def discard_input(bus: "MessageBus", payload: dict) -> None:+ """Best-effort cleanup after the queue mutation has committed."""+ if "input_ref" not in payload:+ return+ try:+ await bus.registry_del(+ MessageBusKeys.chat_input_payloads(payload["session_id"]),+ payload["input_ref"],+ )+ except Exception:+ logger.exception("Could not discard queued input %s.", payload["id"])+++async def cleanup_session(bus: "MessageBus", session_id: str) -> None:+ """Remove empty queue indexes and payloads under the mutation lock."""+ if await bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ ):+ return+ if await bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ ):+ return+ raw = await bus.registry_get(+ MessageBusKeys.chat_input_pending_registry(),+ session_id,+ )+ if raw is not None:+ try:+ user_id = json.loads(raw)["user_id"]+ if not isinstance(user_id, str) or not user_id:+ raise ValueError("Invalid pending-input owner.")+ except (KeyError, TypeError, ValueError):+ logger.warning("Invalid pending-input owner for %s.", session_id)+ else:+ await bus.registry_del(+ MessageBusKeys.chat_input_user_sessions(user_id),+ session_id,+ )+ await bus.registry_drop(MessageBusKeys.chat_input_payloads(session_id))+ await bus.registry_drop(MessageBusKeys.chat_input_claim(session_id))+ await bus.registry_del(+ MessageBusKeys.chat_input_pending_registry(),+ session_id,+ )diff --git a/src/agentscope/app/_manager/_chat_input_queue.py b/src/agentscope/app/_manager/_chat_input_queue.pynew file mode 100644index 000000000..89f71f465--- /dev/null+++ b/src/agentscope/app/_manager/_chat_input_queue.py@@ -0,0 +1,997 @@+# -*- coding: utf-8 -*-+"""Durable FIFO claims, bounded retries, recovery and session wakeups."""+import asyncio+import json+import time+import uuid+from typing import Any, Coroutine, TYPE_CHECKING++from pydantic import TypeAdapter++from ..._logging import logger+from ...event import (+ CustomEvent,+ ExternalExecutionResultEvent,+ UserConfirmResultEvent,+ UserInterruptEvent,+)+from ...message import Msg+from ..message_bus import MessageBusKeys+from ._chat_run_registry import CHAT_RUN_SHUTDOWN+from .._bus_ops import (+ ChatQueueBusyError,+ chat_input_mutation,+ enqueue_run_trigger,+ publish_session_event,+)+from .._chat_input_store import (+ cleanup_session,+ discard_input,+ hydrate_input,+ queue_entry,+)++if TYPE_CHECKING:+ from ..message_bus import MessageBus+ from ..storage import StorageBase+ from .._service import ChatService++_MESSAGE_INPUT_ADAPTER: TypeAdapter = TypeAdapter(Msg | list[Msg])+_MESSAGE_FALLBACK_TICK_SECS = 30.0+_MESSAGE_RECOVERY_LOCK_TTL_SECS = 60+_MESSAGE_RECOVERY_OWNER_FIELD = "owner"+_MESSAGE_RECOVERY_EXPIRES_FIELD = "expires_at"+_MESSAGE_CLAIMED = "claimed"+_MESSAGE_INPUT_PERSISTED = "input_persisted"+_MESSAGE_CANCELLED = "cancelled"+_MESSAGE_FAILED = "failed"+_MESSAGE_COMPLETED = "completed"+++class ChatInputQueue:+ """Own the lifecycle of queued input independently from run dispatch."""++ def __init__(+ self,+ bus: "MessageBus",+ storage: "StorageBase",+ chat_service: "ChatService",+ ) -> None:+ self._bus = bus+ self._storage = storage+ self._chat_service = chat_service+ self._recovery_task: asyncio.Task | None = None+ self._recovery_owner = uuid.uuid4().hex+ self._retry_tasks: set[asyncio.Task] = set()+ self._closed = False++ async def close(self) -> None:+ """Cancel retained timers and release recovery leadership."""+ self._closed = True+ tasks = list(self._retry_tasks)+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ self._retry_tasks.clear()+ self._recovery_task = None+ await self._release_recovery_leadership()++ def schedule_recovery(self) -> None:+ """Retain at most one non-blocking recovery sweep per process."""+ if self._recovery_task is not None and not self._recovery_task.done():+ return+ task = asyncio.create_task(+ self._recover_pending_chat_inputs(),+ name="wakeup-dispatcher:recovery",+ )+ self._recovery_task = task+ self._retry_tasks.add(task)++ def _done(completed: asyncio.Task) -> None:+ self._retry_tasks.discard(completed)+ if self._recovery_task is completed:+ self._recovery_task = None++ task.add_done_callback(_done)++ async def _recover_pending_chat_inputs(self) -> None:+ """Recreate message triggers for durably indexed non-empty FIFOs.++ A cluster-wide renewable leader lease lets only one API process+ perform the O(N) sweeps. Queue probes do not take the foreground+ mutation lock; an empty marker is removed only after a locked+ recheck.+ """+ pushed_count = 0+ try:+ recovery_lock = MessageBusKeys.chat_input_recovery_lock()+ async with self._bus.acquire_lock_bounded(+ recovery_lock,+ ttl_secs=_MESSAGE_RECOVERY_LOCK_TTL_SECS,+ timeout_secs=0.1,+ ):+ now = time.time()+ recovery_state = await self._bus.registry_getall(+ MessageBusKeys.chat_input_recovery_state(),+ )+ try:+ expires_at = float(+ recovery_state.get(+ _MESSAGE_RECOVERY_EXPIRES_FIELD,+ "0",+ ),+ )+ except (TypeError, ValueError):+ expires_at = 0.0+ owner = recovery_state.get(_MESSAGE_RECOVERY_OWNER_FIELD)+ if owner != self._recovery_owner and expires_at > now:+ return+ await self._bus.registry_set(+ MessageBusKeys.chat_input_recovery_state(),+ _MESSAGE_RECOVERY_OWNER_FIELD,+ self._recovery_owner,+ ttl_secs=_MESSAGE_RECOVERY_LOCK_TTL_SECS * 2,+ )+ # Owner and expiry are intentionally separate writes. If the+ # leader dies between them, readers treat missing expiry as+ # zero and immediately allow another process to take over.+ await self._bus.registry_set(+ MessageBusKeys.chat_input_recovery_state(),+ _MESSAGE_RECOVERY_EXPIRES_FIELD,+ str(now + _MESSAGE_FALLBACK_TICK_SECS * 2),+ ttl_secs=_MESSAGE_RECOVERY_LOCK_TTL_SECS * 2,+ )+ pushed_count = await self._recover_pending_chat_inputs_locked()+ except TimeoutError:+ return+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: pending chat queue recovery failed.",+ )+ if pushed_count:+ # Recovery only creates durable triggers. One batched signal+ # wakes the single ``_loop`` consumer; non-leaders and empty+ # sweeps do not generate redundant pub/sub fan-out.+ try:+ await self._bus.publish(MessageBusKeys.wakeup_signal(), {})+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: failed to signal after recovery.",+ )++ async def _release_recovery_leadership(self) -> None:+ """Release this process's recovery lease during graceful shutdown."""+ try:+ recovery_lock = MessageBusKeys.chat_input_recovery_lock()+ async with self._bus.acquire_lock(+ recovery_lock,+ ttl_secs=_MESSAGE_RECOVERY_LOCK_TTL_SECS,+ ):+ recovery_state = await self._bus.registry_getall(+ MessageBusKeys.chat_input_recovery_state(),+ )+ if (+ recovery_state.get(_MESSAGE_RECOVERY_OWNER_FIELD)+ != self._recovery_owner+ ):+ return+ await self._bus.registry_del(+ MessageBusKeys.chat_input_recovery_state(),+ _MESSAGE_RECOVERY_OWNER_FIELD,+ )+ await self._bus.registry_del(+ MessageBusKeys.chat_input_recovery_state(),+ _MESSAGE_RECOVERY_EXPIRES_FIELD,+ )+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: failed to release recovery leadership.",+ )++ async def _recover_pending_chat_inputs_locked(self) -> int:+ """Run one cluster-elected pending-input recovery sweep.++ Returns:+ `int`:+ Number of durable ``queued_message`` triggers pushed. The+ caller publishes one shared signal when this value is+ non-zero.+ """+ pushed_count = 0+ pending_sessions = await self._bus.registry_getall(+ MessageBusKeys.chat_input_pending_registry(),+ )+ inflight_sessions = await self._bus.registry_getall(+ MessageBusKeys.chat_input_inflight_registry(),+ )+ recovery_timeout = MessageBusKeys.CHAT_INPUT_RECOVERY_LOCK_TIMEOUT_SECS+ for session_id in pending_sessions.keys() | inflight_sessions.keys():+ try:+ raw_routing = pending_sessions.get(session_id)+ if raw_routing is not None:+ routing = json.loads(raw_routing)+ else:+ routing = json.loads(inflight_sessions[session_id])+ user_id = routing["user_id"]+ agent_id = routing["agent_id"]+ if not isinstance(user_id, str) or not isinstance(+ agent_id,+ str,+ ):+ raise TypeError(+ "Pending-chat routing ids must be strings.",+ )+ pending = await self._bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ )+ claimed = session_id in inflight_sessions+ if not pending and not claimed:+ # Enqueue can register before pushing. Recheck under the+ # same mutation lock before collecting a stale marker.+ try:+ async with chat_input_mutation(+ self._bus,+ session_id,+ timeout_secs=recovery_timeout,+ ):+ pending = await self._bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ )+ claimed = await self._bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ if not pending and not claimed:+ await cleanup_session(self._bus, session_id)+ except ChatQueueBusyError:+ # Never hold the cluster recovery lease while waiting+ # behind a foreground enqueue/edit operation.+ continue+ if not pending and not claimed:+ continue+ # Reuse the canonical trigger serializer but batch the+ # signal. The sole ``_loop`` drainer consumes it after the+ # recovery method publishes once for the whole sweep.+ await enqueue_run_trigger(+ self._bus,+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ signal=False,+ )+ pushed_count += 1+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: invalid pending-chat registry entry "+ "for session %s.",+ session_id,+ )+ return pushed_count++ async def _is_session_parked(+ self,+ session: object,+ user_id: str,+ agent_id: str,+ ) -> bool:+ """Use the owning agent's canonical pending-tool-call semantics."""+ state = getattr(session, "state", None)+ if not state or not state.context:+ return False+ record = await self._chat_service.resolve_agent(user_id, agent_id)+ return bool(+ state.get_awaiting_tool_calls(record.data.name),+ )++ async def run_resume_serialized(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ input_msg: UserConfirmResultEvent+ | ExternalExecutionResultEvent+ | UserInterruptEvent+ | None,+ ) -> None:+ """Serialize a resume with chat-input claim and parked-state checks.++ Args:+ user_id (`str`):+ User that owns the session.+ session_id (`str`):+ Session whose parked run should resume.+ agent_id (`str`):+ Agent that owns the session.+ input_msg:+ Typed HITL/external-result/interrupt event, or ``None`` for+ a compatible control continuation.+ """+ dispatch_lock = self._bus.acquire_lock_bounded(+ MessageBusKeys.chat_input_dispatch_lock(session_id),+ ttl_secs=MessageBusKeys.CHAT_INPUT_DISPATCH_TTL_SECS,+ timeout_secs=MessageBusKeys.CHAT_INPUT_MUTATION_TIMEOUT_SECS,+ )+ try:+ # pylint: disable-next=unnecessary-dunder-call+ await dispatch_lock.__aenter__()+ except TimeoutError:+ await enqueue_run_trigger(+ self._bus,+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_RESUME,+ inputs=input_msg,+ )+ return+ try:+ await self._chat_service.run(+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ input_msg=input_msg,+ )+ finally:+ await dispatch_lock.__aexit__(None, None, None)++ async def drain_chat_inputs(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ ) -> bool:+ """Run at most one queued ordinary input for one session.++ A durable per-session claim is written before destructive dequeue.+ The input messages are then persisted before execution begins. A+ crash before persistence safely retries the claim; a crash after+ persistence publishes a terminal failure instead of replaying agent+ tools with unknown side effects.++ The long dispatch lease still surrounds generation, but contenders+ use a bounded acquisition wait and leave the durable claim/queue for+ a later nudge rather than blocking a process task indefinitely.++ Args:+ user_id (`str`):+ User that must own the queued turn.+ session_id (`str`):+ Session whose FIFO head may be executed.+ agent_id (`str`):+ Agent that must own the queued turn.++ Returns:+ `bool`:+ ``True`` when one valid claim reached a terminal state and+ the successor should be nudged; ``False`` when there was no+ work or execution was deferred.+ """+ dispatch_lock = self._bus.acquire_lock_bounded(+ MessageBusKeys.chat_input_dispatch_lock(session_id),+ ttl_secs=MessageBusKeys.CHAT_INPUT_DISPATCH_TTL_SECS,+ timeout_secs=MessageBusKeys.CHAT_INPUT_MUTATION_TIMEOUT_SECS,+ )+ try:+ # pylint: disable-next=unnecessary-dunder-call+ await dispatch_lock.__aenter__()+ except TimeoutError:+ return False+ try:+ return await self._drain_chat_inputs_locked(+ user_id,+ session_id,+ agent_id,+ )+ finally:+ await dispatch_lock.__aexit__(None, None, None)++ async def _drain_chat_inputs_locked(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ ) -> bool:+ """Consume one valid claim while holding the dispatch mutex.++ Malformed claims are acknowledged and skipped until the FIFO is+ empty or one valid claim reaches a terminal state.++ Args:+ user_id (`str`):+ User expected to own the claim.+ session_id (`str`):+ Session whose dispatch mutex is already held.+ agent_id (`str`):+ Agent expected to own the claim.++ Returns:+ `bool`:+ ``True`` after consuming one valid/terminal claim;+ ``False`` when empty, busy, running, or HITL-parked.+ """+ while True:+ if await self._bus.is_locked(+ MessageBusKeys.session_lock(session_id),+ ):+ return False+ session = await self._storage.get_session(+ user_id,+ agent_id,+ session_id,+ )+ if session is None or await self._is_session_parked(+ session,+ user_id,+ agent_id,+ ):+ return False++ try:+ claim = await self._claim_chat_input(session_id)+ except ChatQueueBusyError:+ return False+ if claim is None:+ return False+ payload, claim_state = claim+ if claim_state == _MESSAGE_COMPLETED:+ await self._acknowledge_completed(session_id, payload)+ return True+ try:+ queued_user_id = payload["user_id"]+ queued_session_id = payload["session_id"]+ queued_agent_id = payload["agent_id"]+ queued_input = _MESSAGE_INPUT_ADAPTER.validate_python(+ payload["input"],+ )+ messages = (+ queued_input+ if isinstance(queued_input, list)+ else [queued_input]+ )+ if not messages:+ raise ValueError("Queued input list must not be empty.")+ if (+ queued_user_id != user_id+ or queued_session_id != session_id+ or queued_agent_id != agent_id+ ):+ raise ValueError(+ "Queued input ownership does not match its trigger.",+ )+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: dropping malformed queued chat "+ "claim for session %s.",+ session_id,+ )+ await publish_session_event(+ self._bus,+ session_id,+ CustomEvent(+ name="chat_input_failed",+ value={+ "queue_item_id": payload.get("id"),+ "message_ids": [],+ "message": (+ "The queued input is invalid or missing."+ ),+ },+ ).model_dump(mode="json"),+ )+ await self._finish_chat_input_claim(session_id)+ continue++ queue_item_id = payload.get("id")+ if not isinstance(queue_item_id, str) or not queue_item_id:+ queue_item_id = messages[0].id+ message_ids = [msg.id for msg in messages]+ try:+ if claim_state == _MESSAGE_CANCELLED:+ await self._publish_chat_input_cancelled(+ queued_session_id,+ queue_item_id,+ message_ids,+ )+ await self._finish_chat_input_claim(session_id)+ return True+ if claim_state in (_MESSAGE_INPUT_PERSISTED, _MESSAGE_FAILED):+ failed_event = CustomEvent(+ name="chat_input_failed",+ value={+ "queue_item_id": queue_item_id,+ "message_ids": message_ids,+ "message": (+ "The queued message could not be saved after "+ "repeated attempts. Check the server log."+ if claim_state == _MESSAGE_FAILED+ else "Processing stopped after the input was "+ "saved. It was not replayed automatically "+ "to avoid duplicate side effects."+ ),+ },+ )+ await publish_session_event(+ self._bus,+ queued_session_id,+ failed_event.model_dump(mode="json"),+ )+ await self._finish_chat_input_claim(session_id)+ return True++ for message in messages:+ await self._storage.upsert_message(+ queued_user_id,+ queued_session_id,+ message,+ )+ await self._set_chat_input_claim_state(+ session_id,+ payload,+ _MESSAGE_INPUT_PERSISTED,+ )+ claim_state = _MESSAGE_INPUT_PERSISTED+ started_event = CustomEvent(+ name="chat_input_started",+ value={+ "queue_item_id": queue_item_id,+ "message_ids": message_ids,+ "queue_item": {+ "id": queue_item_id,+ "created_at": payload.get(+ "created_at",+ messages[0].created_at,+ ),+ "input": payload["input"],+ },+ },+ )+ await publish_session_event(+ self._bus,+ queued_session_id,+ started_event.model_dump(mode="json"),+ )+ await self._chat_service.run(+ user_id=queued_user_id,+ session_id=queued_session_id,+ agent_id=queued_agent_id,+ input_msg=queued_input,+ queue_item_id=queue_item_id,+ input_persisted=True,+ )+ claim_state = _MESSAGE_COMPLETED+ await self._acknowledge_completed(session_id, payload)+ return True+ except asyncio.CancelledError as exc:+ if claim_state == _MESSAGE_COMPLETED or (+ claim_state == _MESSAGE_CLAIMED+ and exc.args == (CHAT_RUN_SHUTDOWN,)+ ):+ raise+ cleanup_task = asyncio.create_task(+ self._cancel_chat_input_claim(+ session_id,+ queued_session_id,+ queue_item_id,+ message_ids,+ payload,+ ),+ name=f"cancel-chat-claim:{session_id}",+ )+ try:+ await asyncio.shield(cleanup_task)+ except asyncio.CancelledError:+ try:+ await cleanup_task+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: failed to finish cancelled "+ "queued input for session %s.",+ queued_session_id,+ )+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: failed to finish cancelled queued "+ "input for session %s.",+ queued_session_id,+ )+ raise+ except Exception:+ logger.exception(+ "Queued input %s failed in state %s.",+ queue_item_id,+ claim_state,+ )+ if claim_state == _MESSAGE_CLAIMED:+ delay = MessageBusKeys.CHAT_INPUT_RETRY_SECS * payload.get(+ "attempts",+ 1,+ )+ payload["retry_at"] = time.time() + delay+ await self._set_chat_input_claim_state(+ session_id,+ payload,+ _MESSAGE_CLAIMED,+ )+ self.schedule_message_nudge(user_id, session_id, agent_id)+ return False++ async def _claim_chat_input(+ self,+ session_id: str,+ ) -> tuple[dict, str] | None:+ """Durably claim the FIFO head before destructively removing it.++ Args:+ session_id (`str`):+ Session whose FIFO head should be claimed.++ Returns:+ `tuple[dict, str] | None`:+ Raw queue payload and its durable claim state, or ``None``+ when neither an existing claim nor a pending item exists.++ Raises:+ `ChatQueueBusyError`:+ The session mutation lock cannot be acquired promptly.+ """+ async with chat_input_mutation(self._bus, session_id):+ raw = await self._bus.registry_get(+ MessageBusKeys.chat_input_claim(session_id),+ "claim",+ )+ claim = None+ if raw is not None:+ try:+ claim = json.loads(raw)+ if not isinstance(claim["payload"], dict) or claim[+ "state"+ ] not in (+ _MESSAGE_CLAIMED,+ _MESSAGE_INPUT_PERSISTED,+ _MESSAGE_CANCELLED,+ _MESSAGE_FAILED,+ _MESSAGE_COMPLETED,+ ):+ raise ValueError("Invalid chat-input claim.")+ except (KeyError, TypeError, ValueError):+ logger.exception(+ "Deleting malformed claim for session %s.",+ session_id,+ )+ claim = None+ await self._bus.registry_drop(+ MessageBusKeys.chat_input_claim(session_id),+ )+ pending = await self._bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ )+ if claim is None:+ if not pending:+ await self._bus.registry_del(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ await cleanup_session(self._bus, session_id)+ return None+ payload = pending[0][1]+ claim = {"state": _MESSAGE_CLAIMED, "payload": payload}+ payload = claim["payload"]+ if payload.get("retry_at", 0) > time.time():+ return None+ if claim["state"] == _MESSAGE_CLAIMED:+ attempts = payload.get("attempts", 0)+ if attempts >= MessageBusKeys.CHAT_INPUT_MAX_ATTEMPTS:+ claim["state"] = _MESSAGE_FAILED+ else:+ payload["attempts"] = attempts + 1+ # Index first, local durable claim second, dequeue last. A crash+ # at any boundary leaves a discoverable item or harmless marker.+ await self._bus.registry_set(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ json.dumps(+ {+ key: payload.get(key)+ for key in ("id", "user_id", "agent_id")+ },+ ),+ )+ await self._bus.registry_set(+ MessageBusKeys.chat_input_claim(session_id),+ "claim",+ json.dumps(claim),+ )+ if pending and pending[0][1].get("id") == payload.get("id"):+ await self._bus.queue_drain(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ )+ if claim["state"] == _MESSAGE_COMPLETED:+ return payload, _MESSAGE_COMPLETED+ hydrated = await hydrate_input(self._bus, payload)+ return hydrated or payload, claim["state"]++ async def _set_chat_input_claim_state(+ self,+ session_id: str,+ payload: dict,+ state: str,+ ) -> None:+ """Persist a claim state transition under the mutation mutex.++ Internal claim transitions wait for the mutex without the short+ foreground queue timeout. Once an input has been claimed, abandoning+ this transition on ordinary UI contention could make recovery infer+ the wrong execution state.++ Args:+ session_id (`str`):+ Session that owns the in-flight claim.+ payload (`dict`):+ Raw claimed queue item retained for recovery.+ state (`str`):+ Durable state to store for the claim.++ """+ async with self._bus.acquire_lock(+ MessageBusKeys.chat_input_mutation_lock(session_id),+ ttl_secs=MessageBusKeys.CHAT_INPUT_MUTATION_TTL_SECS,+ ):+ await self._bus.registry_set(+ MessageBusKeys.chat_input_claim(session_id),+ "claim",+ json.dumps({"state": state, "payload": queue_entry(payload)}),+ )++ async def _acknowledge_completed(+ self,+ session_id: str,+ payload: dict,+ ) -> None:+ """Retry terminal bookkeeping without running or failing the turn.++ Keep the dispatch lease until completion is durable and acknowledged.+ Cancellation may leave a completed marker for recovery; a hard crash+ before that write remains an unknown outcome, never a safe replay.+ """+ marked = False+ while True:+ try:+ if not marked:+ await self._set_chat_input_claim_state(+ session_id,+ payload,+ _MESSAGE_COMPLETED,+ )+ marked = True+ await self._finish_chat_input_claim(session_id)+ return+ except Exception:+ logger.exception(+ "Retrying completed claim acknowledgement for %s.",+ session_id,+ )+ await asyncio.sleep(MessageBusKeys.CHAT_INPUT_RETRY_SECS)++ async def _finish_chat_input_claim(self, session_id: str) -> None:+ """Acknowledge one claim and garbage-collect an empty marker.++ This terminal acknowledgement uses the reliable internal mutation+ path rather than the bounded foreground path. The operations are+ idempotent, so callers may safely retry after an ambiguous bus error.++ Args:+ session_id (`str`):+ Session whose in-flight claim has reached a terminal state.++ """+ async with self._bus.acquire_lock(+ MessageBusKeys.chat_input_mutation_lock(session_id),+ ttl_secs=MessageBusKeys.CHAT_INPUT_MUTATION_TTL_SECS,+ ):+ raw = await self._bus.registry_get(+ MessageBusKeys.chat_input_claim(session_id),+ "claim",+ )+ await self._bus.registry_drop(+ MessageBusKeys.chat_input_claim(session_id),+ )+ await self._bus.registry_del(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ if raw is not None:+ try:+ payload = json.loads(raw)["payload"]+ if not isinstance(payload, dict):+ raise ValueError("Invalid terminal claim payload.")+ except (KeyError, TypeError, ValueError):+ logger.warning(+ "Skipping malformed terminal claim data for %s.",+ session_id,+ )+ else:+ await discard_input(self._bus, payload)+ await cleanup_session(self._bus, session_id)++ async def _cancel_chat_input_claim(+ self,+ session_id: str,+ event_session_id: str,+ queue_item_id: str,+ message_ids: list[str],+ payload: dict,+ ) -> None:+ """Acknowledge an explicit cancellation and publish its outcome.++ Args:+ session_id (`str`):+ Session that owns the durable claim.+ event_session_id (`str`):+ Session stream that receives the terminal event.+ queue_item_id (`str`):+ Stable id of the cancelled queue item.+ message_ids (`list[str]`):+ Message ids contained in the cancelled turn.+ payload (`dict`):+ Raw claimed payload retained until acknowledgement.+ """+ await self._set_chat_input_claim_state(+ session_id,+ payload,+ _MESSAGE_CANCELLED,+ )+ await self._publish_chat_input_cancelled(+ event_session_id,+ queue_item_id,+ message_ids,+ )+ await self._finish_chat_input_claim(session_id)++ async def _publish_chat_input_cancelled(+ self,+ event_session_id: str,+ queue_item_id: str,+ message_ids: list[str],+ ) -> None:+ """Publish a replayable terminal event for a cancelled claim.++ Args:+ event_session_id (`str`):+ Session stream that receives the event.+ queue_item_id (`str`):+ Stable id of the cancelled queue item.+ message_ids (`list[str]`):+ Message ids contained in the cancelled turn.+ """+ cancelled_event = CustomEvent(+ name="chat_input_cancelled",+ value={+ "queue_item_id": queue_item_id,+ "message_ids": message_ids,+ "message": "Queued message processing was interrupted.",+ },+ )+ await publish_session_event(+ self._bus,+ event_session_id,+ cancelled_event.model_dump(mode="json"),+ )++ def message_pump_done(+ self,+ task: asyncio.Task,+ user_id: str,+ session_id: str,+ agent_id: str,+ ) -> None:+ """Nudge a successor only after a pump consumed a turn.++ Args:+ task (`asyncio.Task`):+ Completed queue-pump task whose result controls progression.+ user_id (`str`):+ User that owns the session queue.+ session_id (`str`):+ Session whose next item may be ready.+ agent_id (`str`):+ Agent that owns the session queue.+ """+ should_nudge = task.cancelled()+ if not should_nudge:+ try:+ should_nudge = task.result() is True+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: chat-input pump failed for "+ "session %s.",+ session_id,+ )+ should_nudge = True+ if not should_nudge:+ return+ self.schedule_message_nudge(user_id, session_id, agent_id)++ def schedule_message_nudge(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ ) -> None:+ """Hold a one-shot fast-path nudge task until it completes.++ Args:+ user_id (`str`):+ User that owns the session queue.+ session_id (`str`):+ Session whose pending/in-flight state should be checked.+ agent_id (`str`):+ Agent that owns the session queue.+ """++ if self._closed:+ return++ async def _nudge() -> None:+ try:+ raw = await self._bus.registry_get(+ MessageBusKeys.chat_input_claim(session_id),+ "claim",+ )+ if raw is not None:+ retry_at = json.loads(raw)["payload"].get("retry_at", 0)+ await asyncio.sleep(+ max(+ MessageBusKeys.CHAT_INPUT_RETRY_SECS,+ retry_at - time.time(),+ ),+ )+ pending = await self._bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ )+ claimed = await self._bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ if pending or claimed:+ await enqueue_run_trigger(+ self._bus,+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher: failed to nudge the next queued "+ "input for session %s.",+ session_id,+ )++ self._track_message_task(+ _nudge(),+ name=f"message-nudge:{session_id}",+ )++ def _track_message_task(+ self,+ coro: Coroutine[Any, Any, object],+ *,+ name: str,+ ) -> None:+ """Create and strongly retain one message-queue helper task.++ Args:+ coro (`Coroutine[Any, Any, object]`):+ Coroutine to schedule.+ name (`str`):+ Diagnostic asyncio task name.+ """+ task = asyncio.create_task(coro, name=name)+ self._retry_tasks.add(task)+ task.add_done_callback(self._retry_tasks.discard)diff --git a/src/agentscope/app/_manager/_chat_run_registry.py b/src/agentscope/app/_manager/_chat_run_registry.pyindex 02b39415e..7e06c4c0b 100644--- a/src/agentscope/app/_manager/_chat_run_registry.py+++ b/src/agentscope/app/_manager/_chat_run_registry.py@@ -20,6 +20,9 @@ from typing import Coroutine, Selffrom ..._logging import logger+CHAT_RUN_SHUTDOWN = "agentscope:shutdown"++class ChatRunRegistry:"""In-process index of active chat-run asyncio tasks, keyed bysession id.@@ -129,7 +132,9 @@ class ChatRunRegistry:)tasks = list(self._tasks.values())for task in tasks:- task.cancel()+ # Preserve an explicit Stop that is already being delivered.+ if not task.cancelling():+ task.cancel(CHAT_RUN_SHUTDOWN)# Wait for every cancel to land; swallow CancelledError per task.await asyncio.gather(*tasks, return_exceptions=True)self._tasks.clear()diff --git a/src/agentscope/app/_manager/_wakeup_dispatcher.py b/src/agentscope/app/_manager/_wakeup_dispatcher.pyindex d706dc057..be23bf4f1 100644--- a/src/agentscope/app/_manager/_wakeup_dispatcher.py+++ b/src/agentscope/app/_manager/_wakeup_dispatcher.py@@ -12,15 +12,18 @@ funnels through this one serial consumer.Each queue entry carries a ``kind`` that selects how a busy session ishandled:-- ``wake`` (idle-session wake-up, ``input_msg=None``): produced only- when no run is registered as the session's inbox consumer, so it- always has something to deliver.-- ``resume`` (a parked HITL run being fed its result): carries the- event the parked run is waiting for.--No kind is ever dropped. A trigger whose session still holds its run-lock is re-queued after a short backoff until the lock frees, then-spawned.+- ``wake`` (idle-session wake-up, ``input_msg=None``): delivers pending+ inbox content and is retried while the session is running.+- ``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.+- ``message`` (an inbound-channel ``Msg``): carries a genuine user message+ and is retried until it can start a run.+- ``queued_message`` (ordinary browser input): drains a per-session FIFO+ only after the current reply is complete and the session is not parked+ on HITL. Durable recovery replaces per-session hot retries.All bus keys live on the :class:`MessageBus` base class (see``enqueue_wakeup`` / ``enqueue_input``, ``dequeue_wakeups``,@@ -42,7 +45,12 @@ from ...event import (from ...message import Msgfrom ...types import ErrorInfo, ErrorType, ReplyFinishedReasonfrom ..message_bus import MessageBusKeys-from .._bus_ops import enqueue_run_trigger, publish_session_event+from ._chat_input_queue import ChatInputQueue++from .._bus_ops import (+ enqueue_run_trigger,+ publish_session_event,+)if TYPE_CHECKING:from ..message_bus import MessageBus@@ -61,6 +69,10 @@ _RESUME_INPUT_ADAPTER: TypeAdapter = TypeAdapter(# to avoid a hot re-enqueue loop while the lock is held._RESUME_RETRY_BACKOFF_SECS = 0.1+# Durably indexed pending queues are revisited at this low frequency.+# This is a crash/lost-signal safety net, not a per-session hot poll.+_MESSAGE_FALLBACK_TICK_SECS = 30.0+class WakeupDispatcher:"""One asyncio task per process, draining the shared trigger queue.@@ -105,18 +117,21 @@ 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._fallback_task: asyncio.Task | None = None+ self._chat_queue = ChatInputQueue(message_bus, storage, chat_service)+ # Detached resume timers. Held+ # so they are not garbage-collected mid-await 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- triggers produced while this process was down (durable in- the queue) are picked up immediately on startup.+ After subscribing, publishes a signal for durable triggers that+ predate process startup. The potentially O(N) pending-session+ recovery sweep runs in a retained background task so application+ startup is not blocked by the number of indexed sessions.Returns:`Self`: This dispatcher instance.@@ -127,7 +142,12 @@ class WakeupDispatcher:name="wakeup-dispatcher",)await ready.wait()- await self._drain_and_dispatch()+ self._fallback_task = asyncio.create_task(+ self._fallback_loop(),+ name="wakeup-dispatcher:fallback",+ )+ await self._bus.publish(MessageBusKeys.wakeup_signal(), {})+ self._chat_queue.schedule_recovery()return selfasync def __aexit__(self, *exc: object) -> None:@@ -141,14 +161,17 @@ class WakeupDispatcher:except asyncio.CancelledError:passself._retry_tasks.clear()- if self._task is None:- return- self._task.cancel()- try:- await self._task- except asyncio.CancelledError:- pass+ for task in (self._fallback_task, self._task):+ if task is None:+ continue+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ self._fallback_task = Noneself._task = None+ await self._chat_queue.close()# ------------------------------------------------------------------# Internals@@ -175,6 +198,24 @@ class WakeupDispatcher:"WakeupDispatcher loop crashed; subscription ended.",)+ async def _fallback_loop(self) -> None:+ """Periodically signal the sole drain loop and schedule recovery."""+ while True:+ await asyncio.sleep(_MESSAGE_FALLBACK_TICK_SECS)+ try:+ # Never drain here: Redis queue_drain is XRANGE + XDEL and+ # therefore requires a single in-process consumer. All+ # actual draining remains serialized in ``_loop``.+ await self._bus.publish(MessageBusKeys.wakeup_signal(), {})+ except Exception: # pylint: disable=broad-except+ logger.exception("WakeupDispatcher fallback signal failed.")+ try:+ self._chat_queue.schedule_recovery()+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "WakeupDispatcher recovery scheduling failed.",+ )+async def _drain_and_dispatch(self) -> None:"""Read up to a batch of trigger entries and dispatch each."""try:@@ -214,7 +255,7 @@ class WakeupDispatcher:session_id: str,agent_id: str,kind: str,- raw_input: dict | None,+ raw_input: dict | list[dict] | None,) -> None:"""Dispatch a single trigger entry by its ``kind``.@@ -226,13 +267,33 @@ class WakeupDispatcher:agent_id (`str`):The agent that owns the session.kind (`str`):- Trigger kind (``wake`` / ``resume``); see module docstring.- raw_input (`dict | None`):+ Trigger kind (``wake`` / ``resume`` / ``message`` /+ ``queued_message``); see the module docstring.+ raw_input (`dict | list[dict] | None`):Serialised input event for ``resume`` triggers, else``None``."""is_resume = kind == MessageBusKeys.WAKEUP_KIND_RESUMEis_message = kind == MessageBusKeys.WAKEUP_KIND_MESSAGE+ is_queued_message = kind == MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE++ # Queued-message triggers are only hints. Avoid storage/lock work+ # for stale completion nudges after the durable queue is empty.+ if is_queued_message:+ pending = await self._bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ )+ claimed = await self._bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ if not pending and not claimed:+ return+ if await self._bus.is_locked(+ MessageBusKeys.chat_input_dispatch_lock(session_id),+ ):+ return# ``resume`` and ``message`` both carry input that must be# delivered — never dropped while the session is busy.carries_input = is_resume or is_message@@ -275,21 +336,18 @@ class WakeupDispatcher:if await self._bus.is_locked(MessageBusKeys.session_lock(session_id),):- # The session is busy, so nothing can be spawned right now:- # re-queue after a short backoff rather than dropping.- #- # ``wake`` needs this as much as the input-carrying kinds. A- # producer only enqueues one after finding no registered- # inbox consumer, which a finished run gives up *before* it- # releases the session lock — so a held lock is no evidence- # that anyone is still going to drain the inbox.- self._schedule_retry(- user_id,- session_id,- agent_id,- kind,- input_msg,- )+ # The durable pending-session registry plus fallback tick+ # revisits browser queues without per-session hot polling.+ # Every other kind carries work that is not durably indexed+ # there, so it must be retried until the run lock is free.+ if not is_queued_message:+ self._schedule_retry(+ user_id,+ session_id,+ agent_id,+ kind,+ input_msg,+ )return# Orphan guard: the queue is unaware of session lifecycle. A@@ -297,10 +355,12 @@ class WakeupDispatcher:# 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- ):+ session = await self._storage.get_session(+ user_id,+ agent_id,+ session_id,+ )+ if session is None:logger.warning("WakeupDispatcher: dropping %s trigger for session %s ""(agent %s, user %s) — session no longer exists in "@@ -329,28 +389,66 @@ class WakeupDispatcher:returntry:- self._registry.spawn(- self._chat_service.run(+ run_coro = (+ self._chat_queue.drain_chat_inputs(+ user_id,+ session_id,+ agent_id,+ )+ if is_queued_message+ else self._chat_queue.run_resume_serialized(user_id=user_id,session_id=session_id,agent_id=agent_id,input_msg=input_msg,- ),+ )+ if is_resume+ else self._chat_service.run(+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ input_msg=input_msg,+ )+ )+ task = self._registry.spawn(+ run_coro,session_id=session_id,name=f"{kind}-run:{session_id}",)+ if is_queued_message:+ # Registry cleanup is registered inside spawn() before this+ # callback. A successful/cancelled pump therefore nudges+ # the next turn only after its local run slot is free.+ task.add_done_callback(+ lambda completed: self._chat_queue.message_pump_done(+ completed,+ user_id,+ session_id,+ agent_id,+ ),+ )+ else:+ task.add_done_callback(+ lambda _completed: self._chat_queue.schedule_message_nudge(+ user_id,+ session_id,+ agent_id,+ ),+ )except RuntimeError:# A local run was registered between the running-check and- # the spawn. Re-queue so neither the carried input nor a- # queued inbox payload is stranded — that run may already be- # past its last drain.- self._schedule_retry(- user_id,- session_id,- agent_id,- kind,- input_msg,- )+ # the spawn. Close the unscheduled coroutine first. Browser+ # queue work remains durably indexed; all other trigger kinds+ # must be re-enqueued because no durable queue owns their input.+ run_coro.close()+ if not is_queued_message:+ self._schedule_retry(+ user_id,+ session_id,+ agent_id,+ kind,+ input_msg,+ )def _schedule_retry(self,@@ -393,7 +491,7 @@ class WakeupDispatcher:user_id=user_id,session_id=session_id,agent_id=agent_id,- kind=kind, # type: ignore[arg-type] # resume | message+ kind=kind, # type: ignore[arg-type]inputs=input_msg,)except asyncio.CancelledError:diff --git a/src/agentscope/app/_router/_chat.py b/src/agentscope/app/_router/_chat.pyindex ae76a39bd..e3ba14d11 100644--- a/src/agentscope/app/_router/_chat.py+++ b/src/agentscope/app/_router/_chat.py@@ -7,11 +7,10 @@ by 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:+Three 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.+- **New user message(s)** are appended to a per-session FIFO and drained+ by :class:`WakeupDispatcher`, one complete reply at a time.- **HITL results** (``UserConfirmResultEvent`` /``ExternalExecutionResultEvent``) are *enqueued* onto the sharedrun-trigger queue and drained by the single@@ -20,15 +19,24 @@ Two trigger paths, deliberately asymmetric:the worker's still-finishing parked run (the old 409 race) — thedispatcher serialises them."""-from fastapi import APIRouter, Depends, HTTPException, status+from typing import Annotated++from fastapi import APIRouter, Depends, HTTPException, Path, Query, statusfrom ..deps import (get_chat_run_registry,get_chat_service,get_current_user_id,get_message_bus,+ get_storage,+)+from ._schema import (+ ChatQueueResponse,+ ChatRequest,+ ChatTriggerResponse,+ ReorderChatQueueRequest,+ UpdateChatQueueItemRequest,)-from ._schema import ChatRequest, ChatTriggerResponsefrom .._manager import ChatRunRegistryfrom .._service import (ChatService,@@ -36,8 +44,19 @@ from .._service import (SubagentHitlProjector,)from ..message_bus import MessageBus, MessageBusKeys-from .._bus_ops import enqueue_run_trigger+from ..storage import StorageBase+from .._bus_ops import (+ ChatQueueBusyError,+ ChatQueueFullError,+ delete_chat_input,+ enqueue_chat_input,+ enqueue_run_trigger,+ list_chat_inputs,+ reorder_chat_inputs,+ update_chat_input,+)from ...event import UserConfirmResultEvent, ExternalExecutionResultEvent+from ...message import Msgchat_router = APIRouter(prefix="/chat",@@ -46,6 +65,278 @@ chat_router = APIRouter()+async def _ensure_session(+ storage: StorageBase,+ user_id: str,+ agent_id: str,+ session_id: str,+) -> None:+ """Ensure the caller owns the target session before queue access.++ Args:+ storage (`StorageBase`):+ Persistent session storage.+ user_id (`str`):+ Authenticated user that must own the session.+ agent_id (`str`):+ Agent that must own the session.+ session_id (`str`):+ Session to validate.++ Raises:+ `HTTPException`:+ HTTP 404 when the session does not exist for this owner.+ """+ session = await storage.get_session(user_id, agent_id, session_id)+ if session is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Session '{session_id}' not found.",+ )+++@chat_router.get(+ "/queue",+ response_model=ChatQueueResponse,+ summary="List editable pending user turns",+)+async def get_chat_queue(+ agent_id: Annotated[+ str,+ Query(description="Agent that owns the target session."),+ ],+ session_id: Annotated[+ str,+ Query(description="Session whose pending FIFO should be listed."),+ ],+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+ message_bus: MessageBus = Depends(get_message_bus),+) -> ChatQueueResponse:+ """Return ordinary user turns that have not begun execution.++ Args:+ agent_id (`str`):+ Agent that owns the target session.+ session_id (`str`):+ Session whose editable pending FIFO should be returned.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected persistent session storage.+ message_bus (`MessageBus`):+ Injected message bus containing the pending FIFO.++ Returns:+ `ChatQueueResponse`:+ Complete editable pending queue in FIFO order.++ Raises:+ `HTTPException`:+ HTTP 404 if the session is not owned by the caller.+ """+ await _ensure_session(storage, user_id, agent_id, session_id)+ items = await list_chat_inputs(message_bus, session_id)+ return ChatQueueResponse(items=items)+++@chat_router.patch(+ "/queue/order",+ response_model=ChatQueueResponse,+ summary="Reorder editable pending user turns",+)+async def reorder_chat_queue(+ request: ReorderChatQueueRequest,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+ message_bus: MessageBus = Depends(get_message_bus),+) -> ChatQueueResponse:+ """Apply an exact FIFO permutation, rejecting stale snapshots.++ Args:+ request (`ReorderChatQueueRequest`):+ Target session and exact desired pending-item permutation.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected persistent session storage.+ message_bus (`MessageBus`):+ Injected message bus containing the pending FIFO.++ Returns:+ `ChatQueueResponse`:+ Complete editable queue after reordering.++ Raises:+ `HTTPException`:+ HTTP 404 if the session is not owned by the caller, HTTP 409+ for a stale or invalid permutation, or HTTP 503 when the queue+ mutation lock cannot be acquired promptly.+ """+ await _ensure_session(+ storage,+ user_id,+ request.agent_id,+ request.session_id,+ )+ try:+ items = await reorder_chat_inputs(+ message_bus,+ user_id,+ request.session_id,+ request.agent_id,+ request.item_ids,+ )+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=str(exc),+ ) from exc+ except ChatQueueBusyError as exc:+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=str(exc),+ ) from exc+ return ChatQueueResponse(items=items)+++@chat_router.patch(+ "/queue/{item_id}",+ response_model=ChatQueueResponse,+ summary="Edit one pending user turn",+)+async def update_chat_queue_item(+ item_id: Annotated[+ str,+ Path(description="Stable id of the pending item to update."),+ ],+ request: UpdateChatQueueItemRequest,+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+ message_bus: MessageBus = Depends(get_message_bus),+) -> ChatQueueResponse:+ """Replace a pending item; started items produce HTTP 409.++ Args:+ item_id (`str`):+ Stable id of the pending item to update.+ request (`UpdateChatQueueItemRequest`):+ Target session and replacement message payload.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected persistent session storage.+ message_bus (`MessageBus`):+ Injected message bus containing the pending FIFO.++ Returns:+ `ChatQueueResponse`:+ Complete editable queue after the update.++ Raises:+ `HTTPException`:+ HTTP 404 if the session is not owned by the caller, HTTP 409+ if the item is no longer pending, or HTTP 503 if the queue is+ busy.+ """+ await _ensure_session(+ storage,+ user_id,+ request.agent_id,+ request.session_id,+ )+ try:+ items = await update_chat_input(+ message_bus,+ user_id,+ request.session_id,+ request.agent_id,+ item_id,+ request.input,+ )+ except LookupError as exc:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=str(exc),+ ) from exc+ except ChatQueueBusyError as exc:+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=str(exc),+ ) from exc+ return ChatQueueResponse(items=items)+++@chat_router.delete(+ "/queue/{item_id}",+ response_model=ChatQueueResponse,+ summary="Delete one pending user turn",+)+async def delete_chat_queue_item(+ item_id: Annotated[+ str,+ Path(description="Stable id of the pending item to delete."),+ ],+ agent_id: Annotated[+ str,+ Query(description="Agent that owns the target session."),+ ],+ session_id: Annotated[+ str,+ Query(description="Session whose pending item should be deleted."),+ ],+ user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),+ message_bus: MessageBus = Depends(get_message_bus),+) -> ChatQueueResponse:+ """Delete a pending item; started items produce HTTP 409.++ Args:+ item_id (`str`):+ Stable id of the pending item to delete.+ agent_id (`str`):+ Agent that owns the target session.+ session_id (`str`):+ Session whose pending item should be deleted.+ user_id (`str`):+ Injected authenticated user id.+ storage (`StorageBase`):+ Injected persistent session storage.+ message_bus (`MessageBus`):+ Injected message bus containing the pending FIFO.++ Returns:+ `ChatQueueResponse`:+ Complete editable queue after deletion.++ Raises:+ `HTTPException`:+ HTTP 404 if the session is not owned by the caller, HTTP 409+ if the item is no longer pending, or HTTP 503 if the queue is+ busy.+ """+ await _ensure_session(storage, user_id, agent_id, session_id)+ try:+ items = await delete_chat_input(+ message_bus,+ user_id,+ session_id,+ agent_id,+ item_id,+ )+ except LookupError as exc:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail=str(exc),+ ) from exc+ except ChatQueueBusyError as exc:+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=str(exc),+ ) from exc+ return ChatQueueResponse(items=items)++@chat_router.post("/",response_model=ChatTriggerResponse,@@ -54,6 +345,7 @@ chat_router = APIRouter(async def chat(request: ChatRequest,user_id: str = Depends(get_current_user_id),+ storage: StorageBase = Depends(get_storage),chat_service: ChatService = Depends(get_chat_service),chat_run_registry: ChatRunRegistry = Depends(get_chat_run_registry),message_bus: MessageBus = Depends(get_message_bus),@@ -67,7 +359,7 @@ async def chat(Accepts the same ``input`` payloads as before:- - ``Msg`` / ``list[Msg]``: new user message(s) — spawned directly.+ - ``Msg`` / ``list[Msg]``: new user message(s) — queued FIFO.- ``UserConfirmResultEvent`` / ``ExternalExecutionResultEvent``:resume a paused tool call (human-in-the-loop) — routed to theowning session and enqueued for the dispatcher.@@ -78,25 +370,27 @@ async def chat(JSON body with ``agent_id``, ``session_id``, and ``input``.user_id (`str`):Injected user id.+ storage (`StorageBase`):+ Injected persistent storage used to verify session ownership.chat_service (`ChatService`):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.+ routing and to enqueue ordinary or resume triggers.Returns:`ChatTriggerResponse`:- Confirms the run was scheduled (for a resume, that it was- enqueued).+ Reports ``queued`` for an accepted ordinary turn and+ ``started`` for continuation or control triggers.Raises:`HTTPException`:- 409 if a chat run for this session is already in flight in- this process (the registry enforces single-run-per-session).- Only direct-spawn paths (new messages / ``None``) can raise- this; the enqueued resume path never does.+ HTTP 404 if an ordinary-message session is not owned by the+ caller; HTTP 409 for a conflicting direct ``None`` continuation;+ HTTP 429 when a queue quota is full; or HTTP 503 when queue+ mutation is temporarily busy."""# ------------------------------------------------------------------# HITL resume — route to the owning session, then enqueue.@@ -135,12 +429,45 @@ async def chat()return ChatTriggerResponse(status="started", session_id=run_session_id)+ # Ordinary user turns always enter the per-session FIFO. Using one+ # path for both idle and busy sessions removes the check-then-spawn+ # race and gives rapid submissions a stable order.+ if isinstance(request.input, (Msg, list)):+ await _ensure_session(+ storage,+ user_id,+ request.agent_id,+ request.session_id,+ )+ try:+ item = await enqueue_chat_input(+ message_bus,+ user_id=user_id,+ session_id=request.session_id,+ agent_id=request.agent_id,+ inputs=request.input,+ )+ except ChatQueueFullError as exc:+ raise HTTPException(+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,+ detail=str(exc),+ ) from exc+ except ChatQueueBusyError as exc:+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=str(exc),+ ) from exc+ return ChatTriggerResponse(+ status="queued",+ session_id=request.session_id,+ queue_item_id=item["id"],+ )+# ------------------------------------------------------------------- # New user message(s) / None — spawn directly. The registry's- # single-run-per-session rule is the desired double-submit guard.+ # ``None`` continuation — retain the direct legacy path.# ------------------------------------------------------------------try:- chat_run_registry.spawn(+ task = chat_run_registry.spawn(chat_service.run(user_id=user_id,session_id=request.session_id,@@ -149,6 +476,13 @@ async def chat(),session_id=request.session_id,)+ task.add_done_callback(+ lambda _completed: chat_service.schedule_queue_nudge(+ user_id,+ request.session_id,+ request.agent_id,+ ),+ )except RuntimeError as e:raise HTTPException(status_code=status.HTTP_409_CONFLICT,diff --git a/src/agentscope/app/_router/_schema/__init__.py b/src/agentscope/app/_router/_schema/__init__.pyindex 1c4da4f16..8b02b8720 100644--- a/src/agentscope/app/_router/_schema/__init__.py+++ b/src/agentscope/app/_router/_schema/__init__.py@@ -11,7 +11,14 @@ from ._channel import (CreateChannelRequest,UpdateChannelRequest,)-from ._chat import ChatRequest, ChatTriggerResponse+from ._chat import (+ ChatRequest,+ ChatTriggerResponse,+ ChatQueueItem,+ ChatQueueResponse,+ ReorderChatQueueRequest,+ UpdateChatQueueItemRequest,+)from ._health import ComponentStatus, HealthResponsefrom ._hub import HubInfofrom ._hub_mcp import InstallMCPRequest, MCPView, UpdateMCPRequest@@ -166,6 +173,10 @@ __all__ = [# Chat"ChatRequest","ChatTriggerResponse",+ "ChatQueueItem",+ "ChatQueueResponse",+ "ReorderChatQueueRequest",+ "UpdateChatQueueItemRequest",# Credential"CreateCredentialRequest","CreateCredentialResponse",diff --git a/src/agentscope/app/_router/_schema/_chat.py b/src/agentscope/app/_router/_schema/_chat.pyindex 5bb68a3ea..b43cd7bda 100644--- a/src/agentscope/app/_router/_schema/_chat.py+++ b/src/agentscope/app/_router/_schema/_chat.py@@ -1,11 +1,15 @@# -*- coding: utf-8 -*-"""The chat endpoint schema."""+from typing import Annotated, Literal, TypeAlias+from pydantic import BaseModel, Fieldfrom ....message import Msgfrom ....event import UserConfirmResultEvent, ExternalExecutionResultEvent+NonEmptyMsgList: TypeAlias = Annotated[list[Msg], Field(min_length=1)]+class ChatRequest(BaseModel):"""Request body for the chat endpoint."""@@ -20,7 +24,7 @@ class ChatRequest(BaseModel):input: (Msg- | list[Msg]+ | NonEmptyMsgList| UserConfirmResultEvent| ExternalExecutionResultEvent| None@@ -30,16 +34,74 @@ class ChatRequest(BaseModel):class ChatTriggerResponse(BaseModel):- """Response body for the fire-and-forget chat trigger.+ """Response body for an accepted chat trigger.- Confirms that the chat run was scheduled. Events produced by the- run arrive separately via the session's SSE stream endpoint.+ An ordinary user turn is accepted into the FIFO with ``queued``;+ continuation and control triggers use ``started``. Resulting events+ arrive separately via the session's SSE stream endpoint."""- status: str = Field(+ status: Literal["started", "queued"] = Field(default="started",- description='Always ``"started"`` when the trigger succeeded.',+ description=(+ '``"queued"`` for an accepted ordinary user turn; '+ '``"started"`` for continuation/control triggers.'+ ),)session_id: str = Field(- description="Echo of the session id the run was started for.",+ description="Session whose queue or run accepted the trigger.",+ )+ queue_item_id: str | None = Field(+ default=None,+ description="Stable queue item id for an ordinary user turn.",+ )+++class ChatQueueItem(BaseModel):+ """One ordinary user turn that has not started execution."""++ id: str = Field(+ description="Stable id used to edit, delete, or reorder this item.",+ )+ created_at: str = Field(+ description="UTC ISO-8601 timestamp recorded when the item queued.",+ )+ input: Msg | NonEmptyMsgList = Field(+ description="One message or non-empty ordered message list.",+ )+++class ChatQueueResponse(BaseModel):+ """Current editable FIFO snapshot for a session."""++ items: list[ChatQueueItem] = Field(+ description="Editable pending turns in FIFO execution order.",+ )+++class UpdateChatQueueItemRequest(BaseModel):+ """Replace the input carried by one pending queue item."""++ agent_id: str = Field(+ description="Agent that owns the target session.",+ )+ session_id: str = Field(+ description="Session whose pending item will be updated.",+ )+ input: Msg | NonEmptyMsgList = Field(+ description="Replacement message or non-empty message list.",+ )+++class ReorderChatQueueRequest(BaseModel):+ """Set the complete pending queue order."""++ agent_id: str = Field(+ description="Agent that owns the target session.",+ )+ session_id: str = Field(+ description="Session whose pending FIFO will be reordered.",+ )+ item_ids: list[str] = Field(+ description="Exact desired permutation of all pending item ids.",)diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex ae06c0ded..5c7c6ab60 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -268,6 +268,19 @@ class ChatService:SubagentHitlProjector(storage),*(extra_projectors or []),]+ # Queue nudges are detached from completed registry tasks so they+ # run only after the local run slot is released. Keep strong+ # references until completion; asyncio's loop retains only weak+ # references to un-awaited tasks.+ self._queue_nudge_tasks: set[asyncio.Task] = set()++ async def resolve_agent(+ self,+ user_id: str,+ agent_id: str,+ ) -> AgentRecord:+ """Resolve an owned or shared agent for execution and queue checks."""+ return await self._access.resolve_agent(user_id, agent_id)async def run(self,@@ -281,6 +294,8 @@ class ChatService:| UserInterruptEvent| None = None,sop_dispatch: str | None = None,+ queue_item_id: str | None = None,+ input_persisted: bool = False,) -> None:"""Drive a chat run to completion.@@ -323,6 +338,10 @@ class ChatService:sop_dispatch (`str | None`, optional):``"<run id>:<step index>"`` when a SOP run dispatchedthis turn, which gives it a submit tool.+ queue_item_id (`str | None`, optional):+ Queue identity for terminal failure reporting.+ input_persisted (`bool`, optional):+ Internal queue caller already saved this initial input."""try:await self._run_impl(@@ -331,6 +350,7 @@ class ChatService:agent_id,input_msg,sop_dispatch,+ input_persisted=input_persisted,)except Exception as e:logger.exception(@@ -341,6 +361,88 @@ class ChatService:agent_id,str(e),)+ if queue_item_id is not None and isinstance(+ input_msg,+ (Msg, list),+ ):+ messages = (+ input_msg+ if isinstance(input_msg, list)+ else [+ input_msg,+ ]+ )+ try:+ event = CustomEvent(+ name="chat_input_failed",+ value={+ "queue_item_id": queue_item_id,+ "message_ids": [msg.id for msg in messages],+ "message": (+ "The queued message could not be processed. "+ "Check the server log for details."+ ),+ },+ )+ await publish_session_event(+ self._message_bus,+ session_id,+ event.model_dump(mode="json"),+ )+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "Failed to publish queued-input failure for "+ "session %s.",+ session_id,+ )++ def schedule_queue_nudge(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ ) -> None:+ """Schedule and strongly retain a one-shot pending-queue nudge.++ Args:+ user_id (`str`):+ User that owns the session queue.+ session_id (`str`):+ Session whose pending/in-flight state should be checked.+ agent_id (`str`):+ Agent that owns the session queue.+ """++ async def _nudge_if_pending() -> None:+ try:+ pending = await self._message_bus.queue_read(+ MessageBusKeys.chat_inputs(session_id),+ max_count=1,+ )+ claimed = await self._message_bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ if pending or claimed:+ await enqueue_run_trigger(+ self._message_bus,+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )+ except Exception: # pylint: disable=broad-except+ logger.exception(+ "Failed to signal queued chat inputs for session %s.",+ session_id,+ )++ task = asyncio.create_task(+ _nudge_if_pending(),+ name=f"chat-queue-nudge:{session_id}",+ )+ self._queue_nudge_tasks.add(task)+ task.add_done_callback(self._queue_nudge_tasks.discard)async def _auto_name_session(self,@@ -796,6 +898,7 @@ class ChatService:| UserInterruptEvent| None,sop_dispatch: str | None = None,+ input_persisted: bool = False,) -> None:"""The actual chat-run body; wrapped by :meth:`run` for errorswallowing. Separated so the try/except doesn't bury the@@ -835,7 +938,7 @@ class ChatService:# the agent is not visible to the caller.# -------------------------------------------------------------try:- agent_record = await self._access.resolve_agent(+ agent_record = await self.resolve_agent(user_id,agent_id,)@@ -1264,7 +1367,9 @@ class ChatService:):# Case A: new reply (user message(s), or# retrigger with empty input)- if isinstance(input_msg, (Msg, list)):+ if isinstance(input_msg, (Msg, list)) and not (+ input_persisted+ ):input_msgs = ([input_msg]if isinstance(input_msg, Msg)@@ -1277,6 +1382,8 @@ class ChatService:msg,)+ # Only the initial queued input was pre-saved.+ input_persisted = Falseasync for event in agent.reply_stream(inputs=input_msg,):diff --git a/src/agentscope/app/_service/_session.py b/src/agentscope/app/_service/_session.pyindex b157c33d8..741ff24e0 100644--- a/src/agentscope/app/_service/_session.py+++ b/src/agentscope/app/_service/_session.py@@ -48,6 +48,7 @@ imports the bus; bus code never imports storage.import asynciofrom enum import StrEnum+from .._chat_input_store import cleanup_sessionfrom ..message_bus import MessageBus, MessageBusKeysfrom ..storage import StorageBasefrom ..workspace_manager import WorkspaceManagerBase@@ -658,6 +659,14 @@ class SessionService:await self._bus.queue_delete(MessageBusKeys.inbox(session_id),)+ await self._bus.queue_delete(+ MessageBusKeys.chat_inputs(session_id),+ )+ await self._bus.registry_del(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )+ await cleanup_session(self._bus, session_id)await self._bus.registry_drop(MessageBusKeys.inbox_consumer(session_id),)diff --git a/src/agentscope/app/_service/_webrtc_session.py b/src/agentscope/app/_service/_webrtc_session.pyindex e23c06495..612baa3be 100644--- a/src/agentscope/app/_service/_webrtc_session.py+++ b/src/agentscope/app/_service/_webrtc_session.py@@ -16,7 +16,7 @@ from ...event import (ReplyStartEvent,)from ...state import AgentState-from .._bus_ops import publish_session_event+from .._bus_ops import nudge_chat_inputs, publish_session_eventfrom ..message_bus import MessageBus, MessageBusKeysfrom ..storage import StorageBasefrom ._webrtc_audio_transport import WebRTCAudioTransport@@ -225,6 +225,12 @@ class WebRTCSession:)self.transport.send_error(str(exc))finally:+ await nudge_chat_inputs(+ self.message_bus,+ self.user_id,+ self.session_id,+ self.agent_id,+ )async with self._close_lock:self._closing = Trueawait self.transport.close()diff --git a/src/agentscope/app/message_bus/_base.py b/src/agentscope/app/message_bus/_base.pyindex 50675f7ca..8589df38f 100644--- a/src/agentscope/app/message_bus/_base.py+++ b/src/agentscope/app/message_bus/_base.py@@ -40,9 +40,11 @@ should fan out at write time — push one entry per recipient inbox usingMode A. The bus stays simple; deduplication is the producer'sresponsibility."""+import asyncio+import jsonfrom abc import ABC, abstractmethodfrom collections.abc import AsyncGenerator-from contextlib import asynccontextmanager+from contextlib import AsyncExitStack, asynccontextmanagerfrom typing import Any, Callable, Selffrom typing_extensions import deprecated@@ -155,6 +157,52 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodslist when the queue is empty."""+ async def queue_read(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ """Read queue entries without removing them.++ Entries are returned oldest first. Callers that need a consistent+ read-modify-write cycle must hold an application-level lock shared+ with every writer of that queue.++ Args:+ key (`str`):+ Queue identifier.+ max_count (`int`, defaults to ``100``):+ Maximum number of entries to return.++ Returns:+ `list[tuple[str, dict]]`:+ ``(entry_id, payload)`` pairs in queue order.+ """+ raise NotImplementedError("This bus does not support editable queues.")++ async def queue_replace(+ self,+ key: str,+ payloads: list[dict],+ ) -> list[str]:+ """Atomically replace a queue's contents with ``payloads``.++ The replacement preserves the supplied order and assigns fresh+ transport-level entry ids. Business-level identities therefore+ belong inside each payload rather than in the transport id.++ Args:+ key (`str`):+ Queue identifier.+ payloads (`list[dict]`):+ Complete new queue contents in oldest-first order.++ Returns:+ `list[str]`:+ Newly assigned transport-level entry ids.+ """+ raise NotImplementedError("This bus does not support editable queues.")+@abstractmethodasync def queue_delete(self, key: str) -> None:"""Delete the drain queue at ``key`` and all of its entries.@@ -355,6 +403,40 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodsif False: # pylint: disable=using-constant-testyield # pylint: disable=unreachable+ @asynccontextmanager+ async def acquire_lock_bounded(+ self,+ key: str,+ *,+ ttl_secs: int = 600,+ timeout_secs: float = 2.0,+ ) -> AsyncGenerator[None, None]:+ """Bound contention waiting without timing out the lock body.++ Custom buses must make cancellation during ``acquire_lock`` safe:+ resolve ambiguous acquisitions and release only their own lease.+ Redis attempts cleanup within its own finite deadline, so cleanup+ may outlast the contention deadline. If transport cleanup times out,+ the lock TTL is the final fallback.++ Args:+ key (`str`): Lock identifier.+ ttl_secs (`int`): Renewable lease duration.+ timeout_secs (`float`): Maximum contention wait.++ Yields:+ `None`: While holding the lock.++ Raises:+ `TimeoutError`: The contention deadline expired.+ """+ async with AsyncExitStack() as stack:+ async with asyncio.timeout(timeout_secs):+ await stack.enter_async_context(+ self.acquire_lock(key, ttl_secs=ttl_secs),+ )+ yield+@abstractmethodasync def is_locked(self, key: str) -> bool:"""Return whether ``key`` currently holds a lock.@@ -544,6 +626,17 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methodsThe stored value, or ``None`` if missing."""+ async def registry_get_many(+ self,+ namespace: str,+ fields: list[str],+ ) -> list[str | None]:+ """Read selected fields in order, using None for missing values.++ Custom buses may override this compatible fallback with a batch read.+ """+ return [await self.registry_get(namespace, field) for field in fields]+@abstractmethodasync def registry_drop(self, namespace: str) -> None:"""Delete the entire registry at ``namespace``.@@ -700,6 +793,30 @@ class MessageBus(ABC): # pylint: disable=too-many-public-methods"""Delete all per-session bus state."""await self.log_trim(self._SESSION_EVENTS_KEY.format(sid=session_id))await self.queue_delete(self._INBOX_KEY.format(sid=session_id))+ await self.queue_delete(MessageBusKeys.chat_inputs(session_id))+ routing = await self.registry_get(+ MessageBusKeys.chat_input_pending_registry(),+ session_id,+ )+ if routing is not None:+ await self.registry_del(+ MessageBusKeys.chat_input_user_sessions(+ json.loads(routing)["user_id"],+ ),+ session_id,+ )+ await self.registry_drop(+ MessageBusKeys.chat_input_payloads(session_id),+ )+ await self.registry_drop(MessageBusKeys.chat_input_claim(session_id))+ await self.registry_del(+ MessageBusKeys.chat_input_pending_registry(),+ session_id,+ )+ await self.registry_del(+ MessageBusKeys.chat_input_inflight_registry(),+ session_id,+ )await self.registry_drop(self._BG_TASKS_KEY.format(sid=session_id))# Inbox -----------------------------------------------------------diff --git a/src/agentscope/app/message_bus/_in_memory_message_bus.py b/src/agentscope/app/message_bus/_in_memory_message_bus.pyindex 39abad03c..85385a2f3 100644--- a/src/agentscope/app/message_bus/_in_memory_message_bus.py+++ b/src/agentscope/app/message_bus/_in_memory_message_bus.py@@ -22,6 +22,7 @@ import timefrom collections import defaultdictfrom collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanager+from copy import deepcopyfrom typing import Callable, Selffrom ._base import MessageBus@@ -34,10 +35,10 @@ class InMemoryMessageBus(Mapping of bus modes to in-memory structures:- - **Mode A (drain queue)** — each key maps to a- :class:`list[tuple[str, dict]]` of ``(entry_id, payload)`` pairs.- ``queue_push`` appends; ``queue_drain`` pops from the front (FIFO)- and deletes the returned entries.+ - **Mode A (drain queue)** — each key maps to+ ``(entry_id, payload, expire_at)`` tuples. ``queue_push`` appends;+ ``queue_drain`` pops from the front (FIFO) and deletes the returned+ entries.- **Mode C (replay log)** — same underlying list structure, but``log_read`` is non-destructive. ``log_trim`` removes entriesin-place.@@ -157,7 +158,7 @@ class InMemoryMessageBus(now = time.monotonic()queue[:] = [e for e in queue if e[2] is None or e[2] > now]expire_at = now + ttl_secs if ttl_secs is not None else None- queue.append((entry_id, payload, expire_at))+ queue.append((entry_id, deepcopy(payload), expire_at))return entry_idasync def queue_drain(@@ -186,7 +187,64 @@ class InMemoryMessageBus(alive = [e for e in q if e[2] is None or e[2] > now]drained = alive[:max_count]self._queues[key] = alive[max_count:]- return [(entry_id, payload) for entry_id, payload, _ in drained]+ return deepcopy(+ [(entry_id, payload) for entry_id, payload, _ in drained],+ )++ async def queue_read(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ """Return queue entries without removing them.++ Args:+ key (`str`):+ Queue identifier.+ max_count (`int`, defaults to ``100``):+ Maximum number of oldest-first entries to return.++ Returns:+ `list[tuple[str, dict]]`:+ Deep-copied ``(entry_id, payload)`` pairs.+ """+ q = self._queues.get(key, [])+ now = time.monotonic()+ alive = [entry for entry in q if entry[2] is None or entry[2] > now]+ if q:+ self._queues[key] = alive+ return deepcopy(+ [+ (entry_id, payload)+ for entry_id, payload, _expire_at in alive[:max_count]+ ],+ )++ async def queue_replace(+ self,+ key: str,+ payloads: list[dict],+ ) -> list[str]:+ """Replace a queue while preserving the supplied payload order.++ Args:+ key (`str`):+ Queue identifier.+ payloads (`list[dict]`):+ Complete replacement contents in oldest-first order.++ Returns:+ `list[str]`:+ Fresh transport-level ids assigned to the new entries.+ """+ entries = [+ (self._next_id(), deepcopy(payload), None) for payload in payloads+ ]+ if entries:+ self._queues[key] = entries+ else:+ self._queues.pop(key, None)+ return [entry_id for entry_id, _payload, _expire_at in entries]async def queue_delete(self, key: str) -> None:"""Delete the drain queue at ``key``.@@ -528,6 +586,15 @@ class InMemoryMessageBus("""return self._registries.get(namespace, {}).get(field)+ async def registry_get_many(+ self,+ namespace: str,+ fields: list[str],+ ) -> list[str | None]:+ """Read only the requested registry fields in their supplied order."""+ registry = self._registries.get(namespace, {})+ return [registry.get(field) for field in fields]+async def registry_drop(self, namespace: str) -> None:"""Delete the entire registry at ``namespace``.diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.pyindex 3f1cc6053..e9623fa30 100644--- a/src/agentscope/app/message_bus/_keys.py+++ b/src/agentscope/app/message_bus/_keys.py@@ -50,6 +50,11 @@ class MessageBusKeys: # pylint: disable=too-many-public-methodsinput, so it is re-queued rather than dropped while the session isrunning."""+ WAKEUP_KIND_QUEUED_MESSAGE: Final = "queued_message"+ """Trigger kind: drain the next ordinary browser input from the+ session's FIFO turn queue. Busy or HITL-parked sessions defer this+ trigger until the current reply has fully finished."""+# ------------------------------------------------------------------# Cross-session UI projection — a generic per-session Redis-hash# store onto which one session can project UI cards owned by another@@ -244,6 +249,159 @@ class MessageBusKeys: # pylint: disable=too-many-public-methods"""return cls._INBOX_CONSUMER.format(sid=session_id)+ # ------------------------------------------------------------------+ # Session user-input queue+ # ------------------------------------------------------------------+ # These keys intentionally use ``session_id`` rather than ``user_id``.+ # This relies on storage assigning globally unique session ids and on+ # every public queue endpoint enforcing session ownership before access.+ # Revisit the key shape if a storage backend ever accepts caller-chosen+ # session ids.++ _CHAT_INPUTS = "agentscope:chat:inputs:{sid}"+ _CHAT_INPUT_DISPATCH_LOCK = "agentscope:chat:inputs:lock:{sid}"+ _CHAT_INPUT_MUTATION_LOCK = "agentscope:chat:inputs:mutation:{sid}"+ _CHAT_INPUT_PENDING_REGISTRY = "agentscope:chat:pending"+ _CHAT_INPUT_INFLIGHT_REGISTRY = "agentscope:chat:inflight"+ _CHAT_INPUT_RECOVERY_LOCK = "agentscope:chat:recovery:lock"+ _CHAT_INPUT_RECOVERY_STATE = "agentscope:chat:recovery:state"+ _CHAT_INPUT_USER_QUOTA_LOCK = "agentscope:chat:quota:lock:{uid}"++ CHAT_INPUT_MAX_LEN: Final = 100+ """Maximum number of pending ordinary user turns per session."""++ CHAT_INPUT_USER_MAX_LEN: Final = 500+ """Maximum pending/in-flight ordinary turns owned by one user."""++ CHAT_INPUT_MUTATION_TTL_SECS: Final = 10+ """Crash lease for short queue mutations."""++ CHAT_INPUT_DISPATCH_TTL_SECS: Final = 30+ """Renewed claim-pump lease; bounds hard-crash queue stalls."""++ CHAT_INPUT_MUTATION_TIMEOUT_SECS: Final = 2.0+ """Maximum foreground wait for a queue mutation lock."""++ CHAT_INPUT_RECOVERY_LOCK_TIMEOUT_SECS: Final = 0.1+ """Maximum recovery-sweep wait for one session mutation lock."""++ CHAT_INPUT_MAX_ATTEMPTS: Final = 3+ """Maximum pre-execution persistence attempts before terminal failure."""++ CHAT_INPUT_RETRY_SECS: Final = 1.0+ """Initial retry backoff; multiplied by the failed attempt count."""++ @classmethod+ def chat_input_payloads(cls, session_id: str) -> str:+ """Return the session-local registry of complete input payloads."""+ return f"agentscope:chat:payloads:{session_id}"++ @classmethod+ def chat_input_claim(cls, session_id: str) -> str:+ """Return the session-local durable claim registry."""+ return f"agentscope:chat:claim:{session_id}"++ @classmethod+ def chat_input_user_sessions(cls, user_id: str) -> str:+ """Return one user's lightweight pending-session index."""+ return f"agentscope:chat:user_sessions:{user_id}"++ @classmethod+ def chat_inputs(cls, session_id: str) -> str:+ """Return the FIFO key for ordinary user turns.++ Args:+ session_id (`str`):+ Session that owns the queue.++ Returns:+ `str`:+ Per-session pending-input queue key.+ """+ return cls._CHAT_INPUTS.format(sid=session_id)++ @classmethod+ def chat_input_dispatch_lock(cls, session_id: str) -> str:+ """Return the cross-process queue-dispatch mutex key.++ Args:+ session_id (`str`):+ Session whose queue drain must be serialized.++ Returns:+ `str`:+ Per-session dispatch-lock key.+ """+ return cls._CHAT_INPUT_DISPATCH_LOCK.format(sid=session_id)++ @classmethod+ def chat_input_mutation_lock(cls, session_id: str) -> str:+ """Return the short-lived queue-mutation mutex key.++ Args:+ session_id (`str`):+ Session whose pending queue may be changed.++ Returns:+ `str`:+ Per-session mutation-lock key.+ """+ return cls._CHAT_INPUT_MUTATION_LOCK.format(sid=session_id)++ @classmethod+ def chat_input_pending_registry(cls) -> str:+ """Return the registry key for sessions with pending input.++ Returns:+ `str`:+ Global pending-session registry key.+ """+ return cls._CHAT_INPUT_PENDING_REGISTRY++ @classmethod+ def chat_input_inflight_registry(cls) -> str:+ """Return the registry key for durably claimed turns.++ Returns:+ `str`:+ Global per-session in-flight claim registry key.+ """+ return cls._CHAT_INPUT_INFLIGHT_REGISTRY++ @classmethod+ def chat_input_user_quota_lock(cls, user_id: str) -> str:+ """Return the per-user pending-turn quota mutex key.++ Args:+ user_id (`str`):+ User whose aggregate quota check must be serialized.++ Returns:+ `str`:+ Per-user quota-lock key.+ """+ return cls._CHAT_INPUT_USER_QUOTA_LOCK.format(uid=user_id)++ @classmethod+ def chat_input_recovery_lock(cls) -> str:+ """Return the cluster-wide recovery-sweep mutex key.++ Returns:+ `str`:+ Recovery leadership lock key.+ """+ return cls._CHAT_INPUT_RECOVERY_LOCK++ @classmethod+ def chat_input_recovery_state(cls) -> str:+ """Return the recovery leadership metadata registry key.++ Returns:+ `str`:+ Registry key containing recovery owner and expiry fields.+ """+ return cls._CHAT_INPUT_RECOVERY_STATE+# ------------------------------------------------------------------# Run trigger queue (wakeup / resume)# ------------------------------------------------------------------diff --git a/src/agentscope/app/message_bus/_redis_message_bus.py b/src/agentscope/app/message_bus/_redis_message_bus.pyindex c4d77f9a6..4990754ab 100644--- a/src/agentscope/app/message_bus/_redis_message_bus.py+++ b/src/agentscope/app/message_bus/_redis_message_bus.py@@ -7,6 +7,7 @@ from collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanagerfrom typing import Any, Callable, Self, TYPE_CHECKING+from ..._logging import loggerfrom ._base import MessageBusif TYPE_CHECKING:@@ -44,6 +45,20 @@ if value then redis.call('HDEL', KEYS[1], ARGV[1]) endreturn value"""+_LOCK_RELEASE_LUA = """+if redis.call('GET', KEYS[1]) == ARGV[1] then+ return redis.call('DEL', KEYS[1])+end+return 0+"""++_LOCK_RENEW_LUA = """+if redis.call('GET', KEYS[1]) == ARGV[1] then+ return redis.call('EXPIRE', KEYS[1], ARGV[2])+end+return 0+"""+class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methods"""Redis-backed implementation of :class:`MessageBus`.@@ -77,6 +92,7 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methodsdb: int = 0,password: str | None = None,connection_pool: ConnectionPool | None = None,+ lock_cleanup_timeout_secs: float = 2.0,**kwargs: Any,) -> None:"""Store connection parameters; the actual pool is created in@@ -98,12 +114,18 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methodslifecycle. When omitted a pool is created from*host*/*port*/*db*/*password* on :meth:`__aenter__`and closed on :meth:`aclose`.+ lock_cleanup_timeout_secs (`float`, defaults to ``2.0``):+ Maximum cancellation cleanup wait before falling back to TTL.**kwargs (`Any`):Extra keyword arguments forwarded to``redis.asyncio.ConnectionPool`` when the pool iscreated internally (e.g. ``max_connections=20``,``socket_timeout=5``)."""+ if lock_cleanup_timeout_secs <= 0:+ raise ValueError("lock_cleanup_timeout_secs must be positive.")+ self._lock_cleanup_timeout_secs = lock_cleanup_timeout_secs+ self._lock_cleanup_tasks: set[asyncio.Task] = set()self._host = hostself._port = portself._db = db@@ -157,6 +179,8 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methodsExternally supplied pools are left open — the caller owns them."""+ for task in tuple(self._lock_cleanup_tasks):+ task.cancel()if self._owned_pool is not None:await self._owned_pool.aclose()self._owned_pool = None@@ -290,6 +314,58 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methodsreturn results+ async def queue_read(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ """Return queue entries without deleting them.++ Args:+ key (`str`):+ Redis Stream key.+ max_count (`int`, defaults to ``100``):+ Maximum number of oldest-first entries to return.++ Returns:+ `list[tuple[str, dict]]`:+ Decoded ``(stream_entry_id, payload)`` pairs.+ """+ entries = await self._client.xrange(key, count=max_count)+ results: list[tuple[str, dict]] = []+ for entry_id, fields in entries:+ raw = fields.get("payload")+ if raw is not None:+ results.append((entry_id, json.loads(raw)))+ return results++ async def queue_replace(+ self,+ key: str,+ payloads: list[dict],+ ) -> list[str]:+ """Replace a Redis Stream queue in one transactional pipeline.++ Args:+ key (`str`):+ Redis Stream key.+ payloads (`list[dict]`):+ Complete replacement contents in oldest-first order.++ Returns:+ `list[str]`:+ Fresh Redis Stream ids assigned to the new entries.+ """+ async with self._client.pipeline(transaction=True) as pipe:+ pipe.delete(key)+ for payload in payloads:+ pipe.xadd(+ key,+ {"payload": json.dumps(payload, ensure_ascii=False)},+ )+ results = await pipe.execute()+ return [str(entry_id) for entry_id in results[1:]]+async def queue_delete(self, key: str) -> None:"""Delete the drain queue at ``key``.@@ -522,6 +598,16 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methods"""return await self._client.hget(namespace, field)+ async def registry_get_many(+ self,+ namespace: str,+ fields: list[str],+ ) -> list[str | None]:+ """Read only the requested registry fields in their supplied order."""+ if not fields:+ return []+ return await self._client.hmget(namespace, fields)+async def registry_drop(self, namespace: str) -> None:"""Delete the entire Hash at ``namespace``.@@ -625,6 +711,56 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methods# Poll interval while waiting for a contested lock._LOCK_RETRY_DELAY_SECS = 0.1+ async def _resolve_cancelled_acquisition(+ self,+ key: str,+ token: str,+ attempt: asyncio.Task,+ ) -> None:+ """Resolve an ambiguous SET within an absolute cleanup deadline."""+ client = self._client++ async def resolve_and_release() -> None:+ try:+ await attempt+ except Exception:+ # A failed response may still represent a committed SET.+ pass+ await client.eval(_LOCK_RELEASE_LUA, 1, key, token)++ def observed(task: asyncio.Task) -> None:+ self._lock_cleanup_tasks.discard(task)+ if not task.cancelled():+ task.exception()++ cleanup = asyncio.create_task(resolve_and_release())+ for task in (attempt, cleanup):+ self._lock_cleanup_tasks.add(task)+ task.add_done_callback(observed)+ deadline = (+ asyncio.get_running_loop().time() + self._lock_cleanup_timeout_secs+ )+ while not cleanup.done():+ remaining = deadline - asyncio.get_running_loop().time()+ if remaining <= 0:+ # Cancelling the Redis request disconnects its in-use socket.+ # Do not wait indefinitely for cleanup of a broken transport.+ cleanup.cancel()+ attempt.cancel()+ logger.warning(+ "Lock acquisition cleanup timed out for %s; "+ "relying on TTL.",+ key,+ )+ return+ try:+ await asyncio.wait({cleanup}, timeout=remaining)+ except asyncio.CancelledError:+ # Further cancellation never resets the absolute deadline.+ continue+ if not cleanup.cancelled() and cleanup.exception() is not None:+ logger.warning("Lock cleanup failed for %s; relying on TTL.", key)+@asynccontextmanagerasync def acquire_lock(self,@@ -642,16 +778,11 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methods- A heartbeat task renews the TTL every ``ttl_secs / 2``seconds while the body runs, so a long-running holderdoes not lose the lease.- - On exit, the heartbeat is cancelled and the lock is- released by GET-then-DEL guarded on the random token —- we never delete a key whose value isn't ours, so a- process whose lease has already expired (and been re-- acquired by someone else) cannot accidentally release- the new holder's lock. The non-atomic GET+DEL race- window opens only after the heartbeat is cancelled, in- a sub-millisecond span; the ``ttl_secs`` lease still has- plenty of time left so the race effectively never- materialises.+ - Renewal and release compare the ownership token atomically.+ - Acquisition cancellation resolves an outstanding SET and releases+ its token within the configured cleanup deadline. If Redis remains+ unavailable, cancelled client tasks are observed and TTL is the+ final fallback. Cleanup never waits indefinitely.Args:key (`str`):@@ -665,7 +796,14 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methodstoken = uuid.uuid4().hex# Acquire (poll until success).while True:- ok = await self._client.set(key, token, nx=True, ex=ttl_secs)+ attempt = asyncio.create_task(+ self._client.set(key, token, nx=True, ex=ttl_secs),+ )+ try:+ ok = await asyncio.shield(attempt)+ except asyncio.CancelledError:+ await self._resolve_cancelled_acquisition(key, token, attempt)+ raiseif ok:breakawait asyncio.sleep(self._LOCK_RETRY_DELAY_SECS)@@ -674,7 +812,13 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methodsasync def _heartbeat() -> None:while True:await asyncio.sleep(max(1.0, ttl_secs / 2))- await self._client.expire(key, ttl_secs)+ await self._client.eval(+ _LOCK_RENEW_LUA,+ 1,+ key,+ token,+ ttl_secs,+ )hb_task = asyncio.create_task(_heartbeat(),@@ -687,16 +831,14 @@ class RedisMessageBus(MessageBus): # pylint: disable=too-many-public-methodshb_task.cancel()try:await hb_task- except asyncio.CancelledError:+ except (asyncio.CancelledError, Exception):pass# Release: only delete if the value still matches our# token. Failures are swallowed (the lease may have# expired naturally, in which case there is nothing to# do).try:- current = await self._client.get(key)- if current == token:- await self._client.delete(key)+ await self._client.eval(_LOCK_RELEASE_LUA, 1, key, token)except Exception: # pylint: disable=broad-exceptpassdiff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.pyindex d6179e48f..0f90b2bcf 100644--- a/src/agentscope/event/_event.py+++ b/src/agentscope/event/_event.py@@ -550,6 +550,14 @@ class CustomEvent(EventBase):changed during a tool call.- ``"team_updated"`` — team membership changed (memberadded / team created or dissolved).+ - ``"chat_input_started"`` — one or more FIFO-queued user+ messages have started their agent turn.+ - ``"chat_input_failed"`` — a dequeued user turn failed before+ the service could produce a usable reply.+ - ``"chat_input_cancelled"`` — an already-started queued turn+ was interrupted and will not be replayed automatically.+ - ``"chat_queue_changed"`` — the editable pending-turn+ snapshot changed after enqueue, edit, delete, or reorder.- ``"mcp_progress"`` — transient MCP tool progress, with``reply_id``, ``tool_call_id``, ``progress``, ``total`` and``message`` in ``value``. Not part of the final tool result.diff --git a/tests/chat_input_queue_test.py b/tests/chat_input_queue_test.pynew file mode 100644index 000000000..168695d32--- /dev/null+++ b/tests/chat_input_queue_test.py@@ -0,0 +1,1203 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Chat queue lifecycle, recovery, resource limits and API regressions."""+import asyncio+import base64+import json+from types import SimpleNamespace+from unittest import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, Mock, patch++import fakeredis.aioredis+from fastapi import FastAPI+from httpx import ASGITransport, AsyncClient+from service_message_bus_test import _make_bus+from service_wakeup_dispatcher_test import _FakeChatService, _FakeStorage++from agentscope.app._bus_ops import (+ _count_user_chat_inputs,+ delete_chat_input,+ enqueue_chat_input,+ list_chat_inputs,+ reorder_chat_inputs,+ update_chat_input,+)+from agentscope.app._manager import (+ CancelDispatcher,+ ChatRunRegistry,+ WakeupDispatcher,+)+from agentscope.app._manager._chat_input_queue import ChatInputQueue+from agentscope.app._manager._chat_run_registry import CHAT_RUN_SHUTDOWN+from agentscope.app._router._chat import chat_router+from agentscope.app._service import ChatService, SessionService+from agentscope.app._service._access import ResourceAccessService+from agentscope.app.access import ResourceKind, ResourceRef+from agentscope.app.deps import (+ get_chat_run_registry,+ get_chat_service,+ get_current_user_id,+ get_message_bus,+ get_storage,+)+from agentscope.app.message_bus import InMemoryMessageBus, MessageBusKeys+from agentscope.message import (+ AssistantMsg,+ Base64Source,+ DataBlock,+ ToolCallBlock,+ ToolResultBlock,+ UserMsg,+)+from agentscope.state import AgentState+++class TestQueueStorageAndRecovery(IsolatedAsyncioTestCase):+ """Exercise real bus primitives, including Redis storage layouts."""++ async def test_failed_dequeue_keeps_claim_out_of_editable_queue(+ self,+ ) -> None:+ """Editing other turns cannot invalidate a durable input claim."""+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self.addAsyncCleanup(redis.aclose)+ for backend in (InMemoryMessageBus(), _make_bus(redis)):+ with self.subTest(backend=type(backend).__name__):+ async with backend as bus:+ original = UserMsg("user", "claimed input")+ items = [+ await enqueue_chat_input(bus, "u", "s", "a", msg)+ for msg in (+ original,+ UserMsg("user", "second"),+ UserMsg("user", "third"),+ )+ ]+ queue = ChatInputQueue(+ bus,+ _FakeStorage(),+ _FakeChatService(),+ )+ with patch.object(+ bus,+ "queue_drain",+ AsyncMock(side_effect=ConnectionError("dequeue")),+ ):+ with self.assertRaises(ConnectionError):+ await queue._claim_chat_input("s")+ raw = await bus.registry_get(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ )+ claimed = json.loads(raw)["payload"]+ await queue.close()+ self.assertEqual(+ await list_chat_inputs(bus, "s"),+ items[1:],+ )+ with self.assertRaises(LookupError):+ await update_chat_input(+ bus,+ "u",+ "s",+ "a",+ items[0]["id"],+ UserMsg("user", "must not replace claim"),+ )+ with self.assertRaises(LookupError):+ await delete_chat_input(+ bus,+ "u",+ "s",+ "a",+ items[0]["id"],+ )+ with self.assertRaises(ValueError):+ await reorder_chat_inputs(+ bus,+ "u",+ "s",+ "a",+ [item["id"] for item in items],+ )+ self.assertEqual(+ await reorder_chat_inputs(+ bus,+ "u",+ "s",+ "a",+ [items[2]["id"], items[1]["id"]],+ ),+ [items[2], items[1]],+ )+ replacement = UserMsg("user", "edited pending input")+ updated = {+ **items[1],+ "input": replacement.model_dump(mode="json"),+ }+ self.assertEqual(+ await update_chat_input(+ bus,+ "u",+ "s",+ "a",+ items[1]["id"],+ replacement,+ ),+ [items[2], updated],+ )+ self.assertEqual(+ await delete_chat_input(+ bus,+ "u",+ "s",+ "a",+ items[2]["id"],+ ),+ [updated],+ )+ self.assertEqual(+ json.loads(+ await bus.registry_get(+ MessageBusKeys.chat_input_payloads("s"),+ claimed["input_ref"],+ ),+ ),+ original.model_dump(mode="json"),+ )+ chat = _FakeChatService()+ restarted = ChatInputQueue(bus, _FakeStorage(), chat)+ self.addAsyncCleanup(restarted.close)+ for _ in range(2):+ self.assertTrue(+ await restarted.drain_chat_inputs("u", "s", "a"),+ )+ self.assertEqual(+ [+ call["input_msg"].model_dump(mode="json")+ for call in chat.calls+ ],+ [+ original.model_dump(mode="json"),+ replacement.model_dump(mode="json"),+ ],+ )+ self.assertEqual(await list_chat_inputs(bus, "s"), [])+ self.assertEqual(+ await bus.registry_getall(+ MessageBusKeys.chat_input_payloads("s"),+ ),+ {},+ )++ async def test_large_attachment_roundtrip_and_cleanup(self) -> None:+ """Base64 bytes survive edits and execution without global copies."""+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self.addAsyncCleanup(redis.aclose)+ for backend in (InMemoryMessageBus(), _make_bus(redis)):+ async with backend as bus:+ message = UserMsg(+ "user",+ [+ DataBlock(+ source=Base64Source(+ data=base64.b64encode(b"x" * 800_000).decode(),+ media_type="image/png",+ ),+ ),+ ],+ )+ first = await enqueue_chat_input(bus, "u", "s", "a", message)+ second = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "next"),+ )+ entries = await bus.queue_read(MessageBusKeys.chat_inputs("s"))+ self.assertLess(len(json.dumps(entries)), 1_000)+ self.assertEqual(+ await list_chat_inputs(bus, "s"),+ [first, second],+ )+ updated = await update_chat_input(+ bus,+ "u",+ "s",+ "a",+ first["id"],+ message,+ )+ self.assertEqual(updated, [first, second])+ self.assertEqual(+ len(+ await bus.registry_getall(+ MessageBusKeys.chat_input_payloads("s"),+ ),+ ),+ 2,+ )+ queue = ChatInputQueue(bus, _FakeStorage(), _FakeChatService())+ self.addAsyncCleanup(queue.close)+ payload, state = await queue._claim_chat_input("s")+ self.assertEqual(state, "claimed")+ self.assertEqual(+ payload["input"],+ message.model_dump(mode="json"),+ )+ self.assertEqual(+ await bus.registry_getall(+ MessageBusKeys.chat_input_inflight_registry(),+ ),+ {+ "s": json.dumps(+ {+ "id": first["id"],+ "user_id": "u",+ "agent_id": "a",+ },+ ),+ },+ )+ local_claim = await bus.registry_get(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ )+ self.assertLess(len(local_claim), 1_000)+ await queue._finish_chat_input_claim("s")+ await delete_chat_input(bus, "u", "s", "a", second["id"])+ for key in (+ MessageBusKeys.chat_input_payloads("s"),+ MessageBusKeys.chat_input_claim("s"),+ MessageBusKeys.chat_input_user_sessions("u"),+ MessageBusKeys.chat_input_pending_registry(),+ MessageBusKeys.chat_input_inflight_registry(),+ ):+ self.assertEqual(await bus.registry_getall(key), {})++ async def test_enqueue_and_claim_do_not_scan_global_indexes(self) -> None:+ """Quota checks read only this user's lightweight sessions."""+ async with InMemoryMessageBus() as bus:+ other = await enqueue_chat_input(+ bus,+ "other",+ "other-s",+ "a",+ UserMsg("u", "other"),+ )+ getall = bus.registry_getall+ read = bus.queue_read++ async def guarded_getall(key: str) -> dict[str, str]:+ self.assertEqual(+ key,+ MessageBusKeys.chat_input_user_sessions("u"),+ )+ return await getall(key)++ async def guarded_read(key: str, max_count: int = 100) -> list:+ self.assertNotEqual(key, MessageBusKeys.chat_inputs("other-s"))+ return await read(key, max_count=max_count)++ queue = ChatInputQueue(bus, _FakeStorage(), _FakeChatService())+ self.addAsyncCleanup(queue.close)+ with patch.object(+ bus,+ "registry_getall",+ guarded_getall,+ ), patch.object(bus, "queue_read", guarded_read):+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "first"),+ )+ await queue._claim_chat_input("s")+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "second"),+ )+ self.assertEqual(await list_chat_inputs(bus, "other-s"), [other])++ async def test_poison_claim_exhausts_budget_then_advances(self) -> None:+ """Persist attempt count across coordinator restarts; skip poison."""+ async with InMemoryMessageBus() as bus:+ storage = _FakeStorage()+ original = storage.upsert_message++ async def persist(+ user: str,+ session: str,+ message: UserMsg,+ ) -> None:+ if message.id == "poison":+ raise RuntimeError("permanently invalid stored message")+ await original(user, session, message)++ storage.upsert_message = AsyncMock(side_effect=persist)+ chat = _FakeChatService()+ bad = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "bad", id="poison"),+ )+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "good", id="successor"),+ )+ with patch.object(MessageBusKeys, "CHAT_INPUT_RETRY_SECS", 0):+ for _ in range(MessageBusKeys.CHAT_INPUT_MAX_ATTEMPTS):+ queue = ChatInputQueue(bus, storage, chat)+ self.assertFalse(+ await queue.drain_chat_inputs("u", "s", "a"),+ )+ await queue.close()+ queue = ChatInputQueue(bus, storage, chat)+ self.addAsyncCleanup(queue.close)+ self.assertTrue(await queue.drain_chat_inputs("u", "s", "a"))+ self.assertTrue(await queue.drain_chat_inputs("u", "s", "a"))+ self.assertEqual(storage.upsert_message.call_count, 4)+ self.assertEqual(+ [call["input_msg"].id for call in chat.calls],+ ["successor"],+ )+ events = await bus.log_read(MessageBusKeys.session_events("s"))+ failed = [+ event["value"]+ for _, event in events+ if event.get("name") == "chat_input_failed"+ ]+ self.assertEqual(+ failed,+ [+ {+ "queue_item_id": bad["id"],+ "message_ids": ["poison"],+ "message": (+ "The queued message could not be saved after "+ "repeated attempts. Check the server log."+ ),+ },+ ],+ )+ self.assertEqual(+ await bus.registry_getall(+ MessageBusKeys.chat_input_user_sessions("u"),+ ),+ {},+ )++ async def test_committed_mutations_survive_notification_failure(+ self,+ ) -> None:+ """Edit, reorder and delete return the state they actually wrote."""+ async with InMemoryMessageBus() as bus:+ first = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "first"),+ )+ second = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "second"),+ )+ with patch.object(+ bus,+ "publish",+ side_effect=RuntimeError("offline"),+ ):+ changed = await update_chat_input(+ bus,+ "u",+ "s",+ "a",+ first["id"],+ UserMsg("u", "edited"),+ )+ self.assertEqual(await list_chat_inputs(bus, "s"), changed)+ ordered = await reorder_chat_inputs(+ bus,+ "u",+ "s",+ "a",+ [second["id"], first["id"]],+ )+ self.assertEqual(ordered, list(reversed(changed)))+ deleted = await delete_chat_input(+ bus,+ "u",+ "s",+ "a",+ first["id"],+ )+ self.assertEqual(deleted, [second])+ self.assertEqual(await list_chat_inputs(bus, "s"), deleted)++ async def test_snapshot_does_not_acquire_mutation_lock(self) -> None:+ """Polling succeeds even while a mutation lock is held."""+ async with InMemoryMessageBus() as bus:+ item = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "read"),+ )+ async with bus.acquire_lock(+ MessageBusKeys.chat_input_mutation_lock("s"),+ ):+ result = await asyncio.wait_for(+ list_chat_inputs(bus, "s"),+ 0.1,+ )+ self.assertEqual(result, [item])++ async def test_session_deletion_clears_payloads_and_user_index(+ self,+ ) -> None:+ """A deleted session leaves neither claimed nor pending payloads."""+ async with InMemoryMessageBus() as bus:+ await enqueue_chat_input(bus, "u", "s", "a", UserMsg("u", "one"))+ await enqueue_chat_input(bus, "u", "s", "a", UserMsg("u", "two"))+ queue = ChatInputQueue(bus, _FakeStorage(), _FakeChatService())+ await queue._claim_chat_input("s")+ service = object.__new__(SessionService)+ service._bus = bus+ await service._purge_session_bus("s")+ self.assertEqual(await list_chat_inputs(bus, "s"), [])+ for key in (+ MessageBusKeys.chat_input_payloads("s"),+ MessageBusKeys.chat_input_claim("s"),+ MessageBusKeys.chat_input_user_sessions("u"),+ MessageBusKeys.chat_input_pending_registry(),+ MessageBusKeys.chat_input_inflight_registry(),+ ):+ self.assertEqual(await bus.registry_getall(key), {})++ async def test_recovery_collects_payload_from_interrupted_enqueue(+ self,+ ) -> None:+ """A crash after payload write but before queue push is collectible."""+ async with InMemoryMessageBus() as bus:+ with patch.object(+ bus,+ "queue_push",+ side_effect=RuntimeError("failed"),+ ):+ with self.assertRaises(RuntimeError):+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "lost"),+ )+ queue = ChatInputQueue(bus, _FakeStorage(), _FakeChatService())+ self.addAsyncCleanup(queue.close)+ self.assertEqual(+ await queue._recover_pending_chat_inputs_locked(),+ 0,+ )+ self.assertEqual(+ await bus.registry_getall(+ MessageBusKeys.chat_input_payloads("s"),+ ),+ {},+ )+ self.assertEqual(+ await bus.registry_getall(+ MessageBusKeys.chat_input_user_sessions("u"),+ ),+ {},+ )+++class TestQueueFailureScope(IsolatedAsyncioTestCase):+ """Match existing agent-state and queue-event contracts."""++ async def test_shared_agent_waits_before_claiming_input(self) -> None:+ """Shared agents retain queued input until pending tools finish."""+ for state in ("asking", "submitted", None):+ with self.subTest(state=state):+ async with InMemoryMessageBus() as bus:+ storage = _FakeStorage()+ record = SimpleNamespace(+ source="user",+ data=SimpleNamespace(name="shared agent"),+ )+ storage.get_agent = AsyncMock(+ side_effect=lambda user_id, _agent_id, owned=record: (+ owned if user_id == "owner" else None+ ),+ )+ session = SimpleNamespace(+ state=AgentState(+ context=[+ AssistantMsg(+ name="shared agent",+ content=[+ ToolCallBlock(+ id="tool",+ name="external",+ input="{}",+ state=state,+ ),+ ]+ if state+ else "done",+ ),+ ],+ ),+ )+ storage.get_session = AsyncMock(return_value=session)+ policy = SimpleNamespace(+ list_accessible=AsyncMock(+ return_value=[+ ResourceRef(+ kind=ResourceKind.AGENT,+ owner_id="owner",+ resource_id="a",+ ),+ ],+ ),+ )+ service = object.__new__(ChatService)+ service._access = ResourceAccessService(storage, policy)+ service.run = AsyncMock()+ queue = ChatInputQueue(bus, storage, service)+ self.addAsyncCleanup(queue.close)+ message = UserMsg("viewer", "next turn")+ item = await enqueue_chat_input(+ bus,+ "viewer",+ "s",+ "a",+ message,+ )+ self.assertEqual(+ await queue.drain_chat_inputs("viewer", "s", "a"),+ state is None,+ )+ self.assertEqual(+ await list_chat_inputs(bus, "s"),+ [item] if state else [],+ )+ self.assertEqual(+ storage.persisted_messages,+ [] if state else [("viewer", "s", message)],+ )+ if state:+ service.run.assert_not_awaited()+ session.state.context = []+ self.assertTrue(+ await queue.drain_chat_inputs("viewer", "s", "a"),+ )+ service.run.assert_awaited_once_with(+ user_id="viewer",+ session_id="s",+ agent_id="a",+ input_msg=message,+ queue_item_id=item["id"],+ input_persisted=True,+ )++ async def test_parked_detection_uses_owning_agent_and_results(+ self,+ ) -> None:+ """Other agents and completed submitted tools do not park a queue."""+ queue = ChatInputQueue(+ InMemoryMessageBus(),+ _FakeStorage(),+ _FakeChatService(),+ )+ for name, state, with_result, expected in (+ ("agent", "asking", False, True),+ ("other", "asking", False, False),+ ("agent", "submitted", False, True),+ ("agent", "submitted", True, False),+ ):+ blocks = [+ ToolCallBlock(+ id="tool",+ name="external",+ input="{}",+ state=state,+ ),+ ]+ if with_result:+ blocks.append(+ ToolResultBlock(id="tool", name="external", output="done"),+ )+ session = SimpleNamespace(+ state=AgentState(+ context=[AssistantMsg(name=name, content=blocks)],+ ),+ )+ self.assertEqual(+ await queue._is_session_parked(session, "u", "a"),+ expected,+ )++ async def test_only_queued_run_failures_emit_queue_event(self) -> None:+ """Channel messages keep their normal error reporting semantics."""+ bus = InMemoryMessageBus()+ service = object.__new__(ChatService)+ service._message_bus = bus+ message = UserMsg("u", "test", id="message")+ with patch.object(+ service,+ "_run_impl",+ side_effect=RuntimeError("failed"),+ ):+ await service.run("u", "s", "a", input_msg=message)+ self.assertEqual(+ await bus.log_read(MessageBusKeys.session_events("s")),+ [],+ )+ await service.run(+ "u",+ "s",+ "a",+ input_msg=message,+ queue_item_id="item",+ )+ events = await bus.log_read(MessageBusKeys.session_events("s"))+ self.assertEqual(+ [(event["name"], event["value"]) for _, event in events],+ [+ (+ "chat_input_failed",+ {+ "queue_item_id": "item",+ "message_ids": ["message"],+ "message": (+ "The queued message could not be processed. "+ "Check the server log for details."+ ),+ },+ ),+ ],+ )+++class TestTerminalChatClaims(IsolatedAsyncioTestCase):+ """Execution outcome is independent from queue acknowledgement."""++ async def asyncSetUp(self) -> None:+ self.bus = await self.enterAsyncContext(InMemoryMessageBus())+ self.storage = _FakeStorage()+ self.chat = _FakeChatService()+ self.queue = ChatInputQueue(self.bus, self.storage, self.chat)+ self.addAsyncCleanup(self.queue.close)+ self.item = await enqueue_chat_input(+ self.bus,+ "u",+ "s",+ "a",+ UserMsg("u", "run once", id="message"),+ )++ async def _event_names(self) -> list[str]:+ return [+ event.get("name")+ for _, event in await self.bus.log_read(+ MessageBusKeys.session_events("s"),+ )+ ]++ async def test_finish_failure_retries_without_replaying_or_failing(+ self,+ ) -> None:+ """A completed run survives a transient failure before deletion."""+ original = self.queue._finish_chat_input_claim+ calls = 0++ async def fail_once(session_id: str) -> None:+ nonlocal calls+ calls += 1+ if calls == 1:+ raw = await self.bus.registry_get(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ )+ assert raw is not None+ self.assertEqual(json.loads(raw)["state"], "completed")+ raise RuntimeError("Redis unavailable")+ await original(session_id)++ with patch.object(+ self.queue,+ "_finish_chat_input_claim",+ fail_once,+ ), patch.object(MessageBusKeys, "CHAT_INPUT_RETRY_SECS", 0):+ self.assertTrue(await self.queue.drain_chat_inputs("u", "s", "a"))+ self.assertEqual(calls, 2)+ self.assertEqual(len(self.chat.calls), 1)+ self.assertEqual(await self._event_names(), ["chat_input_started"])+ self.assertEqual(+ await self.bus.registry_getall(+ MessageBusKeys.chat_input_claim("s"),+ ),+ {},+ )++ async def test_completed_marker_write_retries_under_dispatch_lock(+ self,+ ) -> None:+ """A failed marker write does not re-enter the input-persisted path."""+ original = self.queue._set_chat_input_claim_state+ completed_attempts = 0++ async def fail_once(+ session_id: str,+ payload: dict,+ state: str,+ ) -> None:+ nonlocal completed_attempts+ if state == "completed":+ completed_attempts += 1+ self.assertTrue(+ await self.bus.is_locked(+ MessageBusKeys.chat_input_dispatch_lock("s"),+ ),+ )+ if completed_attempts == 1:+ raise RuntimeError("marker write failed")+ await original(session_id, payload, state)++ with patch.object(+ self.queue,+ "_set_chat_input_claim_state",+ fail_once,+ ), patch.object(MessageBusKeys, "CHAT_INPUT_RETRY_SECS", 0):+ self.assertTrue(await self.queue.drain_chat_inputs("u", "s", "a"))+ self.assertEqual(completed_attempts, 2)+ self.assertEqual(len(self.chat.calls), 1)+ self.assertEqual(await self._event_names(), ["chat_input_started"])++ async def test_restart_silently_acknowledges_completed_without_payload(+ self,+ ) -> None:+ """Completed recovery does not need the attachment blob or execute."""+ payload, _ = await self.queue._claim_chat_input("s")+ await self.queue._set_chat_input_claim_state("s", payload, "completed")+ await self.bus.registry_drop(MessageBusKeys.chat_input_payloads("s"))+ restarted = ChatInputQueue(self.bus, self.storage, self.chat)+ self.addAsyncCleanup(restarted.close)+ self.assertTrue(await restarted.drain_chat_inputs("u", "s", "a"))+ self.assertEqual(self.chat.calls, [])+ self.assertEqual(await self._event_names(), [])+ self.assertEqual(+ await self.bus.registry_getall(+ MessageBusKeys.chat_input_inflight_registry(),+ ),+ {},+ )++ async def test_shutdown_during_finish_keeps_completed_outcome(+ self,+ ) -> None:+ """Cancellation after run does not emit an interrupted outcome."""+ entered = asyncio.Event()++ async def blocked_finish(_session_id: str) -> None:+ entered.set()+ await asyncio.Event().wait()++ with patch.object(+ self.queue,+ "_finish_chat_input_claim",+ blocked_finish,+ ):+ task = asyncio.create_task(+ self.queue.drain_chat_inputs("u", "s", "a"),+ )+ await asyncio.wait_for(entered.wait(), 1)+ task.cancel(CHAT_RUN_SHUTDOWN)+ with self.assertRaises(asyncio.CancelledError):+ await task+ self.assertTrue(await self.queue.drain_chat_inputs("u", "s", "a"))+ self.assertEqual(len(self.chat.calls), 1)+ self.assertEqual(await self._event_names(), ["chat_input_started"])++ async def test_shutdown_preserves_claim_before_execution(self) -> None:+ """Startup recovery retains attempts and dispatches preserved input."""+ entered = asyncio.Event()++ async def blocked_persist(*_args: object) -> None:+ entered.set()+ await asyncio.Event().wait()++ registry = ChatRunRegistry()+ with patch.object(self.storage, "upsert_message", blocked_persist):+ registry.spawn(+ self.queue.drain_chat_inputs("u", "s", "a"),+ session_id="s",+ )+ await asyncio.wait_for(entered.wait(), 1)+ before = await self.bus.registry_get(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ )+ assert before is not None+ expected_claim = json.loads(before)+ self.assertEqual(expected_claim["payload"]["attempts"], 1)+ await registry.__aexit__()+ raw = await self.bus.registry_get(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ )+ assert raw is not None+ self.assertEqual(json.loads(raw), expected_claim)+ self.assertEqual(expected_claim["state"], "claimed")+ self.assertEqual(self.chat.calls, [])+ self.assertEqual(await self._event_names(), [])++ # Remove the original enqueue hint: only startup recovery can wake it.+ await self.bus.queue_drain(MessageBusKeys.wakeup_queue())+ resumed_claims = []+ persist = self.storage.upsert_message++ async def record_recovery_attempt(*args: object) -> None:+ resumed = await self.bus.registry_get(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ )+ assert resumed is not None+ resumed_claims.append(json.loads(resumed))+ await persist(*args)++ async with ChatRunRegistry() as resumed_registry:+ dispatcher = WakeupDispatcher(+ message_bus=self.bus,+ storage=self.storage,+ chat_service=self.chat,+ chat_run_registry=resumed_registry,+ )+ recover_pending = (+ dispatcher._chat_queue._recover_pending_chat_inputs_locked+ )+ with patch.object(+ self.storage,+ "upsert_message",+ record_recovery_attempt,+ ), patch.object(+ dispatcher._chat_queue,+ "_recover_pending_chat_inputs_locked",+ wraps=recover_pending,+ ) as recovery:+ async with dispatcher:+ await asyncio.wait_for(self.chat.notify.wait(), 1)+ task = resumed_registry.get("s")+ if task is not None:+ await asyncio.wait_for(task, 1)+ recovery.assert_awaited_once()+ expected_claim["payload"]["attempts"] = 2+ self.assertEqual(resumed_claims, [expected_claim])+ self.assertEqual(+ [call["input_msg"].id for call in self.chat.calls],+ ["message"],+ )+ self.assertEqual(await self._event_names(), ["chat_input_started"])+ self.assertEqual(+ await self.bus.registry_getall(+ MessageBusKeys.chat_input_claim("s"),+ ),+ {},+ )++ async def test_explicit_stop_is_not_overwritten_by_shutdown(self) -> None:+ """A pending user Stop remains terminal even before run starts."""+ entered = asyncio.Event()++ async def blocked_persist(*_args: object) -> None:+ entered.set()+ await asyncio.Event().wait()++ registry = ChatRunRegistry()+ cancel = CancelDispatcher(self.bus, registry, Mock())+ with patch.object(self.storage, "upsert_message", blocked_persist):+ registry.spawn(+ self.queue.drain_chat_inputs("u", "s", "a"),+ session_id="s",+ )+ await asyncio.wait_for(entered.wait(), 1)+ cancel._interrupt_session("s")+ await registry.__aexit__()+ self.assertEqual(self.chat.calls, [])+ self.assertEqual(await self._event_names(), ["chat_input_cancelled"])+ self.assertEqual(+ await self.bus.registry_getall(+ MessageBusKeys.chat_input_claim("s"),+ ),+ {},+ )+ self.assertFalse(await self.queue.drain_chat_inputs("u", "s", "a"))+++class TestChatInputPayloads(IsolatedAsyncioTestCase):+ """Preserve large input compatibility and read only referenced payloads."""++ async def test_large_attachment_can_be_enqueued_and_edited(self) -> None:+ """Inputs exceeding the removed attachment budget remain accepted."""+ message = UserMsg(+ "u",+ [+ DataBlock(+ source=Base64Source(+ data=base64.b64encode(+ b"x" * (24 * 1024 * 1024 + 1),+ ).decode(),+ media_type="image/png",+ ),+ ),+ ],+ )+ async with InMemoryMessageBus() as bus:+ item = await enqueue_chat_input(bus, "u", "s", "a", message)+ self.assertEqual(item["input"], message.model_dump(mode="json"))+ self.assertEqual(+ await update_chat_input(+ bus,+ "u",+ "s",+ "a",+ item["id"],+ message,+ ),+ [item],+ )+ self.assertEqual(await list_chat_inputs(bus, "s"), [item])++ async def test_large_text_can_be_sent_and_edited_over_http(self) -> None:+ """The HTTP queue accepts text beyond the removed one MB budget."""+ async with InMemoryMessageBus() as bus:+ storage, chat, registry = (+ _FakeStorage(),+ _FakeChatService(),+ ChatRunRegistry(),+ )+ app = FastAPI()+ app.include_router(chat_router)+ app.dependency_overrides = {+ get_current_user_id: lambda: "u",+ get_storage: lambda: storage,+ get_message_bus: lambda: bus,+ get_chat_service: lambda: chat,+ get_chat_run_registry: lambda: registry,+ }+ body = {+ "agent_id": "a",+ "session_id": "s",+ "input": UserMsg("u", "x" * 1_000_001).model_dump(mode="json"),+ }+ async with AsyncClient(+ transport=ASGITransport(app=app),+ base_url="http://test",+ ) as client:+ sent = await client.post("/chat/", json=body)+ self.assertEqual(sent.status_code, 200)+ items = await list_chat_inputs(bus, "s")+ self.assertEqual(len(items), 1)+ self.assertEqual(+ sent.json(),+ {+ "status": "queued",+ "session_id": "s",+ "queue_item_id": items[0]["id"],+ },+ )+ self.assertEqual(items[0]["input"], body["input"])+ body["input"] = UserMsg("u", "y" * 1_000_002).model_dump(+ mode="json",+ )+ edited = await client.patch(+ f"/chat/queue/{items[0]['id']}",+ json=body,+ )+ items[0]["input"] = body["input"]+ self.assertEqual(+ (edited.status_code, edited.json()),+ (200, {"items": items}),+ )+ self.assertEqual(await list_chat_inputs(bus, "s"), items)+ self.assertEqual(chat.calls, [])++ async def test_list_uses_one_hmget_for_only_pending_references(+ self,+ ) -> None:+ """Reading a queue does not fetch unrelated or inflight attachments."""+ redis = fakeredis.aioredis.FakeRedis(decode_responses=True)+ self.addAsyncCleanup(redis.aclose)+ async with _make_bus(redis) as bus:+ first = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "first"),+ )+ second = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "second"),+ )+ await bus.registry_set(+ MessageBusKeys.chat_input_payloads("s"),+ "unreferenced",+ "do not read",+ )+ entries = await bus.queue_read(MessageBusKeys.chat_inputs("s"))+ refs = [entry["input_ref"] for _, entry in entries]+ with patch.object(+ redis,+ "hmget",+ wraps=redis.hmget,+ ) as many, patch.object(+ redis,+ "hget",+ wraps=redis.hget,+ ) as single, patch.object(+ redis,+ "hgetall",+ side_effect=AssertionError("whole hash"),+ ):+ self.assertEqual(+ await list_chat_inputs(bus, "s"),+ [first, second],+ )+ many.assert_called_once_with(+ MessageBusKeys.chat_input_payloads("s"),+ refs,+ )+ single.assert_called_once_with(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ )+++class TestCorruptQueueMetadata(IsolatedAsyncioTestCase):+ """Malformed data cannot repeatedly break quotas or terminal cleanup."""++ async def test_corrupt_claim_counts_without_blocking_enqueue(+ self,+ ) -> None:+ """Bad claim metadata uses one quota slot without causing a 500."""+ async with InMemoryMessageBus() as bus:+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "pending"),+ )+ for raw in ("{broken", "[]", "{}", '{"id": []}', '{"id": null}'):+ with self.subTest(raw=raw):+ await bus.registry_set(+ MessageBusKeys.chat_input_inflight_registry(),+ "s",+ raw,+ )+ self.assertEqual(+ await _count_user_chat_inputs(bus, "u"),+ 2,+ )+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "accepted"),+ )+ self.assertEqual(len(await list_chat_inputs(bus, "s")), 2)++ async def test_corrupt_terminal_claim_does_not_prevent_cleanup(+ self,+ ) -> None:+ """Invalid claim data does not prevent removal of empty indexes."""+ for raw in ("{broken", "[]", "{}", '{"payload": []}'):+ with self.subTest(raw=raw):+ async with InMemoryMessageBus() as bus:+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "pending"),+ )+ queue = ChatInputQueue(+ bus,+ _FakeStorage(),+ _FakeChatService(),+ )+ await queue._claim_chat_input("s")+ await bus.registry_set(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ raw,+ )+ await queue._finish_chat_input_claim("s")+ for key in (+ MessageBusKeys.chat_input_claim("s"),+ MessageBusKeys.chat_input_payloads("s"),+ MessageBusKeys.chat_input_inflight_registry(),+ MessageBusKeys.chat_input_pending_registry(),+ MessageBusKeys.chat_input_user_sessions("u"),+ ):+ self.assertEqual(await bus.registry_getall(key), {})++ async def test_corrupt_payload_is_failed_and_successor_runs(self) -> None:+ """A broken referenced payload cannot block subsequent inputs."""+ async with InMemoryMessageBus() as bus:+ bad = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "bad"),+ )+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("u", "next", id="next"),+ )+ await bus.registry_set(+ MessageBusKeys.chat_input_payloads("s"),+ bad["id"],+ "{broken",+ )+ chat = _FakeChatService()+ queue = ChatInputQueue(bus, _FakeStorage(), chat)+ self.assertTrue(await queue.drain_chat_inputs("u", "s", "a"))+ self.assertEqual(+ [call["input_msg"].id for call in chat.calls],+ ["next"],+ )+ events = await bus.log_read(MessageBusKeys.session_events("s"))+ self.assertEqual(+ [+ (event["name"], event["value"]["queue_item_id"])+ for _, event in events+ if event["name"] == "chat_input_failed"+ ],+ [("chat_input_failed", bad["id"])],+ )diff --git a/tests/in_memory_message_bus_test.py b/tests/in_memory_message_bus_test.pyindex 00c4a0173..5bbccbdba 100644--- a/tests/in_memory_message_bus_test.py+++ b/tests/in_memory_message_bus_test.py@@ -13,7 +13,7 @@ from contextlib import AsyncExitStackfrom unittest import IsolatedAsyncioTestCasefrom unittest.mock import patch-from agentscope.app.message_bus import InMemoryMessageBus+from agentscope.app.message_bus import InMemoryMessageBus, MessageBusKeysfrom agentscope.app.message_bus import _in_memory_message_bus as _bus@@ -72,6 +72,40 @@ class TestQueuePrimitive(IsolatedAsyncioTestCase):"""Deleting a non-existent queue does not raise."""await self.bus.queue_delete("never-existed")+ async def test_queue_read_is_non_destructive(self) -> None:+ """Queue management can inspect entries without consuming them."""+ await self.bus.queue_push("k", {"i": 1})+ await self.bus.queue_push("k", {"i": 2})+ first = await self.bus.queue_read("k", max_count=10)+ second = await self.bus.queue_read("k", max_count=10)+ self.assertEqual(+ [payload for _entry_id, payload in first],+ [{"i": 1}, {"i": 2}],+ )+ self.assertEqual(first, second)++ async def test_queue_read_returns_deep_copies(self) -> None:+ """Mutating a read snapshot cannot corrupt the stored queue."""+ original = {"nested": {"value": 1}}+ await self.bus.queue_push("k", original)+ original["nested"]["value"] = 2++ first = await self.bus.queue_read("k", max_count=1)+ first[0][1]["nested"]["value"] = 3+ second = await self.bus.queue_read("k", max_count=1)++ self.assertEqual(second[0][1]["nested"]["value"], 1)++ async def test_queue_replace_preserves_new_order(self) -> None:+ """An editable queue can be atomically replaced and reordered."""+ await self.bus.queue_push("k", {"i": 1})+ await self.bus.queue_replace("k", [{"i": 3}, {"i": 2}])+ entries = await self.bus.queue_drain("k", max_count=10)+ self.assertEqual(+ [payload for _entry_id, payload in entries],+ [{"i": 3}, {"i": 2}],+ )+async def test_queue_isolation_between_keys(self) -> None:"""Pushes to different keys are independent."""await self.bus.queue_push("a", {"x": 1})@@ -514,7 +548,21 @@ class TestDomainHelpers(IsolatedAsyncioTestCase):sid = "s-purge"await self.bus.session_publish_event(sid, {"e": 1})await self.bus.inbox_push(sid, {"m": 1})+ await self.bus.queue_push(+ MessageBusKeys.chat_inputs(sid),+ {"input": {"id": "queued"}},+ )await self.bus.bg_task_register(sid, "t1", "{}")+ await self.bus.registry_set(+ MessageBusKeys.chat_input_pending_registry(),+ sid,+ '{"user_id":"u","agent_id":"a"}',+ )+ await self.bus.registry_set(+ MessageBusKeys.chat_input_inflight_registry(),+ sid,+ '{"state":"claimed","payload":{"id":"queued"}}',+ )await self.bus.session_purge(sid)@@ -523,7 +571,26 @@ class TestDomainHelpers(IsolatedAsyncioTestCase):await self.bus.inbox_drain(sid, max_count=10),[],)+ self.assertEqual(+ await self.bus.queue_drain(+ MessageBusKeys.chat_inputs(sid),+ max_count=10,+ ),+ [],+ )self.assertEqual(await self.bus.bg_task_list(sid), {})+ self.assertFalse(+ await self.bus.registry_exists(+ MessageBusKeys.chat_input_pending_registry(),+ sid,+ ),+ )+ self.assertFalse(+ await self.bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ sid,+ ),+ )async def test_task_cancel_pub_sub(self) -> None:"""``task_publish_cancel`` → ``task_subscribe_cancel``diff --git a/tests/service_cancel_dispatcher_test.py b/tests/service_cancel_dispatcher_test.pyindex 3a3dad47e..acca2745c 100644--- a/tests/service_cancel_dispatcher_test.py+++ b/tests/service_cancel_dispatcher_test.py@@ -28,7 +28,7 @@ from agentscope.app.message_bus import MessageBusfrom agentscope.message import ToolResultState-class _FakeBus(MessageBus):+class _FakeBus(MessageBus): # pylint: disable=too-many-public-methods"""In-memory bus with just enough behaviour for the dispatcher.Only the cancel-broadcast channel is exercised here; the other@@ -60,6 +60,20 @@ class _FakeBus(MessageBus):) -> list[tuple[str, dict]]:return []+ async def queue_read(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ return []++ async def queue_replace(+ self,+ key: str,+ payloads: list[dict],+ ) -> list[str]:+ return []+async def queue_delete(self, key: str) -> None:return Nonediff --git a/tests/service_chat_run_context_test.py b/tests/service_chat_run_context_test.pyindex 0eb4f59a6..203046164 100644--- a/tests/service_chat_run_context_test.py+++ b/tests/service_chat_run_context_test.py@@ -9,6 +9,8 @@ from unittest.mock import AsyncMock, patchfrom agentscope.agent import ContextConfig, ReActConfigfrom agentscope.app._service import ChatService+from agentscope.app._bus_ops import enqueue_chat_input+from agentscope.app._manager._chat_input_queue import ChatInputQueuefrom agentscope.app.message_bus import InMemoryMessageBusfrom agentscope.app.storage import (AgentData,@@ -21,6 +23,7 @@ from agentscope.app.storage import (TTSModelConfig,)from agentscope.middleware import TTSMiddleware+from agentscope.message import UserMsgfrom agentscope.state import AgentState@@ -91,7 +94,17 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):"""A missing profile skips TTS while the worker still replies."""await self._assert_worker_run(tts_available=False)- async def _assert_worker_run(self, tts_available: bool) -> None:+ async def test_queue_and_direct_input_each_saved_once(self) -> None:+ """Queue persistence replaces the initial save in ChatService."""+ for queued in (False, True):+ with self.subTest(queued=queued):+ await self._assert_worker_run(True, queued=queued)++ async def _assert_worker_run(+ self,+ tts_available: bool,+ queued: bool | None = None,+ ) -> None:"""Exercise assembly and reply with or without a usable TTS model."""user_id = "user-1"worker_agent = AgentRecord(@@ -206,6 +219,7 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):resource_access_service=_Access(),custom_agent_cls=_Agent,)+ message = UserMsg("user", "run once") if queued is not None else Nonewith (patch("agentscope.app._service._chat.get_toolkit",@@ -220,15 +234,44 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):"agentscope.app._service._chat.publish_session_event",new_callable=AsyncMock,) as publish,+ patch.object(+ storage,+ "upsert_message",+ wraps=storage.upsert_message,+ ) as save,):if not tts_available:get_tts_model.return_value = None- await service._run_impl(- user_id,- worker_session.id,- worker_agent.id,- None,- )+ if queued:+ queue = ChatInputQueue(service._message_bus, storage, service)+ self.addAsyncCleanup(queue.close)+ await enqueue_chat_input(+ service._message_bus,+ user_id,+ worker_session.id,+ worker_agent.id,+ message,+ )+ self.assertTrue(+ await queue.drain_chat_inputs(+ user_id,+ worker_session.id,+ worker_agent.id,+ ),+ )+ else:+ await service._run_impl(+ user_id,+ worker_session.id,+ worker_agent.id,+ message,+ )+ if message is not None:+ save.assert_awaited_once_with(+ user_id,+ worker_session.id,+ message,+ )failures = [call.args[2]@@ -283,7 +326,7 @@ class TestRunContextResolution(IsolatedAsyncioTestCase):"get_team_calls": 1,"team_role": "worker","channel_tools": [],- "replies": [None],+ "replies": [message],"tts_models": ([get_tts_model.return_value] if tts_available else []),diff --git a/tests/service_inbox_middleware_test.py b/tests/service_inbox_middleware_test.pyindex 5b8d8924c..8dbd23b5c 100644--- a/tests/service_inbox_middleware_test.py+++ b/tests/service_inbox_middleware_test.py@@ -35,7 +35,7 @@ from agentscope.message import ()-class _FakeBus(MessageBus):+class _FakeBus(MessageBus): # pylint: disable=too-many-public-methods"""In-memory bus that only implements the inbox API needed by:class:`InboxMiddleware`. All other primitives raise ``NotImplemented``to make accidental dependencies obvious."""@@ -71,6 +71,22 @@ class _FakeBus(MessageBus):self._queues[key] = self._queues.get(key, [])[max_count:]return entries+ async def queue_read(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ return list(self._queues.get(key, [])[:max_count])++ async def queue_replace(+ self,+ key: str,+ payloads: list[dict],+ ) -> list[str]:+ entries = [(self._alloc_id(), payload) for payload in payloads]+ self._queues[key] = entries+ return [entry_id for entry_id, _payload in entries]+async def queue_delete(self, key: str) -> None:self._queues.pop(key, None)diff --git a/tests/service_index_task_consumer_test.py b/tests/service_index_task_consumer_test.pyindex 4f292f171..7a64a4c48 100644--- a/tests/service_index_task_consumer_test.py+++ b/tests/service_index_task_consumer_test.py@@ -29,7 +29,7 @@ from agentscope.app._service import IndexTaskConsumerfrom agentscope.app.message_bus import MessageBus, MessageBusKeys-class _FakeBus(MessageBus):+class _FakeBus(MessageBus): # pylint: disable=too-many-public-methods"""In-memory bus with just enough behaviour for the consumer.Implements the primitives the consumer actually uses@@ -71,6 +71,25 @@ class _FakeBus(MessageBus):self.queues[key] = self.queues.get(key, [])[max_count:]return entries+ async def queue_read(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ return list(self.queues.get(key, [])[:max_count])++ async def queue_replace(+ self,+ key: str,+ payloads: list[dict],+ ) -> list[str]:+ entries = []+ for payload in payloads:+ self._next += 1+ entries.append((str(self._next), payload))+ self.queues[key] = entries+ return [entry_id for entry_id, _payload in entries]+async def queue_delete(self, key: str) -> None:self.queues.pop(key, None)diff --git a/tests/service_message_bus_test.py b/tests/service_message_bus_test.pyindex 4b9a6a83a..a1f755996 100644--- a/tests/service_message_bus_test.py+++ b/tests/service_message_bus_test.py@@ -17,7 +17,11 @@ from unittest.mock import patchimport fakeredis.aioredisfrom utils import AnyString-from agentscope.app.message_bus import MessageBus, RedisMessageBus+from agentscope.app.message_bus import (+ InMemoryMessageBus,+ MessageBus,+ RedisMessageBus,+)def _make_bus(@@ -41,12 +45,17 @@ def _make_bus("""Bus subclass that returns the supplied fakeredis client oncontext entry instead of building a real one."""+ def __init__(self) -> None:+ """Initialize the bus and declare the test-owned client."""+ super().__init__()+ self._client: fakeredis.aioredis.FakeRedis | None = None+async def __aenter__(self) -> "RedisMessageBus":self._client = fake_redisreturn selfasync def aclose(self) -> None:- # The fakeredis client is owned by the test, not the bus.+ """Detach the client without closing the test-owned connection."""self._client = Nonereturn _FakeBus()@@ -86,6 +95,28 @@ class TestQueuePrimitive(IsolatedAsyncioTestCase):self.assertEqual([p["i"] for _id, p in first], [0, 1, 2])self.assertEqual([p["i"] for _id, p in rest], [3, 4])+ async def test_queue_read_is_non_destructive(self) -> None:+ """Queue management can inspect entries without consuming them."""+ await self.bus.queue_push("k", {"i": 1})+ await self.bus.queue_push("k", {"i": 2})+ first = await self.bus.queue_read("k", max_count=10)+ second = await self.bus.queue_read("k", max_count=10)+ self.assertEqual(+ [payload for _entry_id, payload in first],+ [{"i": 1}, {"i": 2}],+ )+ self.assertEqual(first, second)++ async def test_queue_replace_preserves_new_order(self) -> None:+ """An editable Redis queue is transactionally replaced."""+ await self.bus.queue_push("k", {"i": 1})+ await self.bus.queue_replace("k", [{"i": 3}, {"i": 2}])+ entries = await self.bus.queue_drain("k", max_count=10)+ self.assertEqual(+ [payload for _entry_id, payload in entries],+ [{"i": 3}, {"i": 2}],+ )+async def test_drain_reads_and_deletes_in_one_command(self) -> None:"""Reading and deleting as two commands lets a competingconsumer land in between, read the same entry and dispatch it a@@ -328,6 +359,161 @@ class TestLockPrimitive(IsolatedAsyncioTestCase):["first-in", "first-out", "second-in"],)+ async def test_timeout_resolves_committed_set_before_returning(+ self,+ ) -> None:+ """An acquisition timeout cannot leave an unrenewed committed lock."""+ committed = asyncio.Event()+ release_response = asyncio.Event()+ original = self.fr.set++ async def delayed_set(*args: Any, **kwargs: Any) -> object:+ result = await original(*args, **kwargs)+ committed.set()+ await release_response.wait()+ return result++ async def acquire() -> None:+ async with self.bus.acquire_lock_bounded(+ "delayed",+ ttl_secs=10,+ timeout_secs=0.01,+ ):+ self.fail("Timed-out acquisition entered the body.")++ with patch.object(self.fr, "set", delayed_set):+ task = asyncio.create_task(acquire())+ await asyncio.wait_for(committed.wait(), 1)+ await asyncio.sleep(0.03)+ self.assertFalse(task.done())+ release_response.set()+ with self.assertRaises(TimeoutError):+ await asyncio.wait_for(task, 1)+ self.assertEqual(await self.fr.get("delayed"), None)++ async def test_repeated_cancel_does_not_release_new_owner(self) -> None:+ """Late SET cleanup is shielded and checks its ownership token."""+ committed = asyncio.Event()+ release_response = asyncio.Event()+ original = self.fr.set++ async def delayed_set(*args: Any, **kwargs: Any) -> object:+ result = await original(*args, **kwargs)+ committed.set()+ await release_response.wait()+ return result++ async def acquire() -> None:+ async with self.bus.acquire_lock("cancelled", ttl_secs=10):+ self.fail("Cancelled acquisition entered the body.")++ with patch.object(self.fr, "set", delayed_set):+ task = asyncio.create_task(acquire())+ await asyncio.wait_for(committed.wait(), 1)+ task.cancel()+ await asyncio.sleep(0)+ task.cancel()+ await asyncio.sleep(0)+ await original("cancelled", "new-owner", ex=10)+ release_response.set()+ with self.assertRaises(asyncio.CancelledError):+ await asyncio.wait_for(task, 1)+ self.assertEqual(await self.fr.get("cancelled"), "new-owner")++ async def test_stalled_set_cleanup_has_absolute_deadline(self) -> None:+ """Repeated cancellation cannot extend cleanup of a stuck SET."""+ committed, release = asyncio.Event(), asyncio.Event()+ original = self.fr.set++ async def blocked_set(*args: Any, **kwargs: Any) -> object:+ result = await original(*args, **kwargs)+ committed.set()+ await release.wait()+ return result++ async def acquire() -> None:+ async with self.bus.acquire_lock("stalled", ttl_secs=10):+ self.fail("Cancelled acquisition entered its body.")++ self.bus._lock_cleanup_timeout_secs = 0.03+ with patch.object(self.fr, "set", blocked_set):+ task = asyncio.create_task(acquire())+ try:+ await asyncio.wait_for(committed.wait(), 1)+ task.cancel()+ for _ in range(5):+ await asyncio.sleep(0.01)+ task.cancel()+ done, _ = await asyncio.wait({task}, timeout=0.3)+ self.assertEqual(done, {task})+ self.assertTrue(task.cancelled())+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ self.assertEqual(self.bus._lock_cleanup_tasks, set())+ self.assertGreater(await self.fr.ttl("stalled"), 0)+ finally:+ release.set()+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ async def test_stalled_release_does_not_block_acquisition_cancellation(+ self,+ ) -> None:+ """The deadline also covers release Lua, not only the SET response."""+ committed, response, releasing, release = (+ asyncio.Event(),+ asyncio.Event(),+ asyncio.Event(),+ asyncio.Event(),+ )+ original_set = self.fr.set++ async def delayed_set(*args: Any, **kwargs: Any) -> object:+ result = await original_set(*args, **kwargs)+ committed.set()+ await response.wait()+ return result++ async def blocked_eval(*_args: Any, **_kwargs: Any) -> None:+ releasing.set()+ await release.wait()++ async def acquire() -> None:+ async with self.bus.acquire_lock("stalled-release", ttl_secs=10):+ self.fail("Cancelled acquisition entered its body.")++ self.bus._lock_cleanup_timeout_secs = 0.03+ with patch.object(self.fr, "set", delayed_set), patch.object(+ self.fr,+ "eval",+ blocked_eval,+ ):+ task = asyncio.create_task(acquire())+ try:+ await asyncio.wait_for(committed.wait(), 1)+ task.cancel()+ response.set()+ await asyncio.wait_for(releasing.wait(), 1)+ done, _ = await asyncio.wait({task}, timeout=0.3)+ self.assertEqual(done, {task})+ self.assertTrue(task.cancelled())+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ self.assertEqual(self.bus._lock_cleanup_tasks, set())+ finally:+ response.set()+ release.set()+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ async def test_heartbeat_does_not_renew_another_owner(self) -> None:+ """A stale holder cannot extend or delete a replacement lease."""+ async with self.bus.acquire_lock("ownership", ttl_secs=2):+ await self.fr.set("ownership", "replacement", ex=20)+ await asyncio.sleep(1.05)+ self.assertGreater(await self.fr.ttl("ownership"), 10)+ self.assertEqual(await self.fr.get("ownership"), "replacement")+class TestSessionRunAutoTrimsLog(IsolatedAsyncioTestCase):"""``session_run.__aexit__`` must trim the session's replay log@@ -509,6 +695,35 @@ class TestRegistryPrimitive(IsolatedAsyncioTestCase):await self._stack.aclose()await self.fr.aclose()+ async def test_batch_read_preserves_order_missing_and_custom_bus_fallback(+ self,+ ) -> None:+ """The optional primitive has compatible semantics on every backend."""+ memory_bus = await self._stack.enter_async_context(+ InMemoryMessageBus(),+ )+ for bus in (memory_bus, self.bus):+ await bus.registry_set("test-batch", "one", "1")+ await bus.registry_set("test-batch", "two", "2")+ fields = ["two", "absent", "one", "two"]+ self.assertEqual(+ await bus.registry_get_many("test-batch", fields),+ ["2", None, "1", "2"],+ )+ self.assertEqual(+ await MessageBus.registry_get_many(+ bus,+ "test-batch",+ fields,+ ),+ ["2", None, "1", "2"],+ )+ self.assertEqual(+ await bus.registry_get_many("test-batch", []),+ [],+ )+ self.assertNotIn("registry_get_many", MessageBus.__abstractmethods__)+async def test_set_then_exists_and_getall(self) -> None:"""``registry_set`` stores a field under a namespace; ``exists``is True, ``getall`` returns the full mapping."""@@ -714,3 +929,15 @@ class TestBaseClassIsAbstract(IsolatedAsyncioTestCase):with self.assertRaises(TypeError):# pylint: disable=abstract-class-instantiatedMessageBus() # type: ignore[abstract]++ async def test_historical_bus_remains_instantiable(self) -> None:+ """Optional editable-queue methods do not add abstract requirements."""+ self.assertFalse(+ {"queue_read", "queue_replace", "acquire_lock_bounded"}+ & MessageBus.__abstractmethods__,+ )+ bus = InMemoryMessageBus()+ with self.assertRaises(NotImplementedError):+ await MessageBus.queue_read(bus, "unsupported")+ with self.assertRaises(NotImplementedError):+ await MessageBus.queue_replace(bus, "unsupported", [])diff --git a/tests/service_wakeup_dispatcher_test.py b/tests/service_wakeup_dispatcher_test.pyindex c66c63d7e..1b39fe374 100644--- a/tests/service_wakeup_dispatcher_test.py+++ b/tests/service_wakeup_dispatcher_test.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--# pylint: disable=protected-access+# pylint: disable=protected-access,missing-function-docstring,unused-argument"""Tests for :class:`WakeupDispatcher` — one-per-process consumer of theshared wake-up queue + signal channel.@@ -15,12 +15,42 @@ Verifies the four behaviours that callers rely on:- Malformed entries are logged and skipped, not raised."""import asyncio+import jsonfrom contextlib import asynccontextmanager+from types import SimpleNamespacefrom typing import Any, AsyncGenerator, Callablefrom unittest import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, Mock, call as mock_call, patch+from fastapi import HTTPException+from pydantic import ValidationError++from agentscope.app import _bus_opsfrom agentscope.app._manager import ChatRunRegistry, WakeupDispatcher-from agentscope.app.message_bus import MessageBus, MessageBusKeys+from agentscope.app._service import ChatService+from agentscope.app._bus_ops import (+ ChatQueueBusyError,+ ChatQueueFullError,+ delete_chat_input,+ enqueue_chat_input,+ enqueue_run_trigger,+ list_chat_inputs,+ reorder_chat_inputs,+ update_chat_input,+)+from agentscope.app._manager._chat_input_queue import ChatInputQueue+from agentscope.app.message_bus import (+ InMemoryMessageBus,+ MessageBus,+ MessageBusKeys,+)+from agentscope.app._router._chat import chat as chat_endpoint+from agentscope.app._router._schema import (+ ChatRequest,+ UpdateChatQueueItemRequest,+)+from agentscope.state import AgentState+from agentscope.message import AssistantMsg, ToolCallBlock, UserMsgclass _FakeStorage:@@ -33,6 +63,8 @@ class _FakeStorage:def __init__(self) -> None:self.missing_session_ids: set[str] = set()+ self.parked_session_ids: set[str] = set()+ self.persisted_messages: list[tuple[str, str, object]] = []async def get_session(self,@@ -43,10 +75,38 @@ class _FakeStorage:"""Get a session id from the orphan guard."""if session_id in self.missing_session_ids:return None- return object()+ context = []+ if session_id in self.parked_session_ids:+ context = [+ AssistantMsg(+ name="agent",+ content=[+ ToolCallBlock(+ id="tc",+ name="needs_confirmation",+ input="{}",+ state="asking",+ ),+ ],+ ),+ ]+ return SimpleNamespace(state=AgentState(context=context))++ async def get_agent(self, _user_id: str, _agent_id: str) -> object:+ """Return the agent name used by canonical HITL detection."""+ return SimpleNamespace(data=SimpleNamespace(name="agent"))++ async def upsert_message(+ self,+ user_id: str,+ session_id: str,+ message: object,+ ) -> None:+ """Record messages durably persisted before queued execution."""+ self.persisted_messages.append((user_id, session_id, message))-class _FakeBus(MessageBus):+class _FakeBus(MessageBus): # pylint: disable=too-many-public-methods"""In-memory bus with just enough behaviour for the dispatcher.Implements the four primitives the dispatcher uses@@ -60,6 +120,9 @@ class _FakeBus(MessageBus):self._channels: dict[str, asyncio.Queue] = {}self._next = 0self._locks: set[str] = set()+ self.log_appends: list[tuple[str, dict]] = []+ self.registries: dict[str, dict[str, str]] = {}+ self.wakeup_drain_task_names: list[str] = []def _channel(self, key: str) -> asyncio.Queue:return self._channels.setdefault(key, asyncio.Queue())@@ -83,10 +146,34 @@ class _FakeBus(MessageBus):*,max_count: int,) -> list[tuple[str, dict]]:+ if key == MessageBusKeys.wakeup_queue():+ task = asyncio.current_task()+ self.wakeup_drain_task_names.append(+ task.get_name() if task is not None else "",+ )entries = self.queues.get(key, [])[:max_count]self.queues[key] = self.queues.get(key, [])[max_count:]return entries+ async def queue_read(+ self,+ key: str,+ max_count: int = 100,+ ) -> list[tuple[str, dict]]:+ return list(self.queues.get(key, [])[:max_count])++ async def queue_replace(+ self,+ key: str,+ payloads: list[dict],+ ) -> list[str]:+ entries = []+ for payload in payloads:+ self._next += 1+ entries.append((str(self._next), payload))+ self.queues[key] = entries+ return [entry_id for entry_id, _payload in entries]+async def queue_delete(self, key: str) -> None:self.queues.pop(key, None)@@ -99,6 +186,7 @@ class _FakeBus(MessageBus):max_len: int | None = None,ttl_secs: int | None = None,) -> str:+ self.log_appends.append((key, payload))return "n/a"async def log_read(@@ -159,9 +247,7 @@ class _FakeBus(MessageBus):async def unlock(self, key: str) -> None:pass- # Mode F — registry (unused by WakeupDispatcher; raise so any- # accidental dependency surfaces immediately rather than silently- # passing through a stub).+ # Mode F — registryasync def registry_set(self,namespace: str,@@ -170,7 +256,7 @@ class _FakeBus(MessageBus):*,ttl_secs: int | None = None,) -> None:- raise NotImplementedError+ self.registries.setdefault(namespace, {})[field] = valueasync def registry_set_if(self,@@ -187,23 +273,23 @@ class _FakeBus(MessageBus):raise NotImplementedErrorasync def registry_del(self, namespace: str, field: str) -> None:- raise NotImplementedError+ self.registries.get(namespace, {}).pop(field, None)async def registry_exists(self, namespace: str, field: str) -> bool:- raise NotImplementedError+ return field in self.registries.get(namespace, {})async def registry_getall(self, namespace: str) -> dict[str, str]:- raise NotImplementedError+ return dict(self.registries.get(namespace, {}))async def registry_get(self,namespace: str,field: str,) -> str | None:- raise NotImplementedError+ return self.registries.get(namespace, {}).get(field)async def registry_drop(self, namespace: str) -> None:- raise NotImplementedError+ self.registries.pop(namespace, None)class _FakeChatService:@@ -213,12 +299,18 @@ class _FakeChatService:self.calls: list[dict] = []self.notify = asyncio.Event()+ async def resolve_agent(self, _user_id: str, _agent_id: str) -> object:+ """Return the agent used by queue parked-state checks."""+ return SimpleNamespace(data=SimpleNamespace(name="agent"))+async def run(self,user_id: str,session_id: str,agent_id: str,input_msg: Any = None,+ queue_item_id: str | None = None,+ input_persisted: bool = False,) -> None:"""Record the call and signal a waiter."""self.calls.append(@@ -232,15 +324,121 @@ class _FakeChatService:self.notify.set()+class _BlockingChatService(_FakeChatService):+ """Holds the first turn so later submissions exercise FIFO queuing."""++ def __init__(self, bus: MessageBus) -> None:+ super().__init__()+ self._bus = bus+ self.release_first = asyncio.Event()++ async def run(+ self,+ user_id: str,+ session_id: str,+ agent_id: str,+ input_msg: Any = None,+ queue_item_id: str | None = None,+ input_persisted: bool = False,+ ) -> None:+ await super().run(+ user_id,+ session_id,+ agent_id,+ input_msg,+ queue_item_id,+ input_persisted,+ )+ if len(self.calls) == 1:+ await self.release_first.wait()+ await enqueue_run_trigger(+ self._bus,+ user_id=user_id,+ session_id=session_id,+ agent_id=agent_id,+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )++async def _yield_a_few_times(ticks: int = 8) -> None:"""Yield the event loop a few times so spawned tasks make progress."""for _ in range(ticks):await asyncio.sleep(0)-class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):+class TestWakeupDispatcherDispatch( # pylint: disable=too-many-public-methods+ IsolatedAsyncioTestCase,+):"""Verifies the signal-driven dispatch path."""+ async def test_run_trigger_can_be_batched_without_signal(self) -> None:+ """Recovery can reuse canonical serialization and signal once."""+ bus = _FakeBus()++ await enqueue_run_trigger(+ bus,+ user_id="u",+ session_id="s",+ agent_id="a",+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ signal=False,+ )++ triggers = await bus.queue_read(+ MessageBusKeys.wakeup_queue(),+ max_count=10,+ )+ self.assertEqual(+ triggers[0][1],+ {+ "user_id": "u",+ "session_id": "s",+ "agent_id": "a",+ "kind": MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ "input": None,+ },+ )+ self.assertEqual(+ bus._channel(MessageBusKeys.wakeup_signal()).qsize(),+ 0,+ )++ async def test_direct_message_and_queued_message_are_distinct(+ self,+ ) -> None:+ """Channel messages carry input instead of draining the web FIFO."""+ bus = _FakeBus()+ chat = _FakeChatService()+ message = UserMsg("channel-user", "from channel", id="channel-msg")++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await enqueue_run_trigger(+ bus,+ user_id="u",+ session_id="channel-session",+ agent_id="a",+ kind=MessageBusKeys.WAKEUP_KIND_MESSAGE,+ inputs=message,+ )+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(+ chat.calls,+ [+ {+ "user_id": "u",+ "session_id": "channel-session",+ "agent_id": "a",+ "input_msg": message,+ },+ ],+ )+async def test_signal_drives_dispatch(self) -> None:"""A wake-up signal causes the queue to be drained and eachentry dispatched as a chat run."""@@ -398,6 +596,360 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):],)+ async def test_wrong_user_message_trigger_never_deletes_queue(+ self,+ ) -> None:+ """A trigger-scoped ownership miss only drops that trigger."""++ class _OwnerStorage(_FakeStorage):+ async def get_session(+ self,+ user_id: str,+ _agent_id: str,+ _session_id: str,+ ) -> object | None:+ return object() if user_id == "owner" else None++ bus = _FakeBus()+ chat = _FakeChatService()+ existing = await enqueue_chat_input(+ bus,+ "owner",+ "shared-sid",+ "a",+ UserMsg("user", "must survive"),+ )+ await bus.queue_drain(MessageBusKeys.wakeup_queue(), max_count=10)+ await bus.registry_del(+ MessageBusKeys.chat_input_pending_registry(),+ "shared-sid",+ )+ await bus.queue_push(+ MessageBusKeys.wakeup_queue(),+ {+ "user_id": "attacker",+ "session_id": "shared-sid",+ "agent_id": "a",+ "kind": MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ "input": None,+ },+ )++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_OwnerStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await _yield_a_few_times()++ self.assertEqual(chat.calls, [])+ self.assertEqual(+ [item["id"] for item in await list_chat_inputs(bus, "shared-sid")],+ [existing["id"]],+ )++ async def test_empty_queued_list_is_dropped_without_stopping_pump(+ self,+ ) -> None:+ """A legacy malformed item cannot crash or strand later turns."""+ bus = _FakeBus()+ chat = _FakeChatService()+ queue_key = MessageBusKeys.chat_inputs("s")+ base = {+ "user_id": "u",+ "session_id": "s",+ "agent_id": "a",+ "created_at": "2026-01-01T00:00:00Z",+ }+ await bus.queue_push(queue_key, {**base, "id": "empty", "input": []})+ valid = UserMsg("user", "after malformed")+ await bus.queue_push(+ queue_key,+ {+ **base,+ "id": "valid",+ "input": valid.model_dump(mode="json"),+ },+ )+ await enqueue_run_trigger(+ bus,+ user_id="u",+ session_id="s",+ agent_id="a",+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(len(chat.calls), 1)+ self.assertEqual(chat.calls[0]["input_msg"].id, valid.id)++ async def test_claim_retries_when_input_persistence_failed(self) -> None:+ """A pre-persistence failure leaves a durable, retryable claim."""++ class _FailOnceStorage(_FakeStorage):+ def __init__(self) -> None:+ super().__init__()+ self.fail_once = True++ async def upsert_message(+ self,+ user_id: str,+ session_id: str,+ message: object,+ ) -> None:+ if self.fail_once:+ self.fail_once = False+ raise RuntimeError("storage unavailable")+ await super().upsert_message(user_id, session_id, message)++ bus = _FakeBus()+ storage = _FailOnceStorage()+ chat = _FakeChatService()+ dispatcher = WakeupDispatcher(+ message_bus=bus,+ storage=storage,+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ )+ await enqueue_chat_input(+ bus,+ "u",+ "claim-retry",+ "a",+ UserMsg("user", "persist me", id="claim-message"),+ )++ with patch.object(MessageBusKeys, "CHAT_INPUT_RETRY_SECS", 0):+ self.assertFalse(+ await dispatcher._chat_queue.drain_chat_inputs(+ "u",+ "claim-retry",+ "a",+ ),+ )++ self.assertEqual(+ await bus.queue_read(+ MessageBusKeys.chat_inputs("claim-retry"),+ max_count=1,+ ),+ [],+ )+ claim = json.loads(+ (+ await bus.registry_getall(+ MessageBusKeys.chat_input_claim("claim-retry"),+ )+ )["claim"],+ )+ self.assertEqual(claim["state"], "claimed")++ self.assertTrue(+ await dispatcher._chat_queue.drain_chat_inputs(+ "u",+ "claim-retry",+ "a",+ ),+ )+ self.assertEqual(len(chat.calls), 1)+ self.assertEqual(chat.calls[0]["input_msg"].id, "claim-message")+ self.assertFalse(+ await bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ "claim-retry",+ ),+ )++ async def test_recovered_post_persistence_claim_is_not_replayed(+ self,+ ) -> None:+ """Unknown tool side effects turn a recovered claim into failure."""+ bus = _FakeBus()+ storage = _FakeStorage()+ chat = _FakeChatService()+ dispatcher = WakeupDispatcher(+ message_bus=bus,+ storage=storage,+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ )+ await enqueue_chat_input(+ bus,+ "u",+ "claim-failed",+ "a",+ UserMsg("user", "do not replay", id="persisted-message"),+ )+ payload, _state = await dispatcher._chat_queue._claim_chat_input(+ "claim-failed",+ )+ await dispatcher._chat_queue._set_chat_input_claim_state(+ "claim-failed",+ payload,+ "input_persisted",+ )++ self.assertTrue(+ await dispatcher._chat_queue.drain_chat_inputs(+ "u",+ "claim-failed",+ "a",+ ),+ )+ self.assertEqual(chat.calls, [])+ self.assertIn(+ "chat_input_failed",+ [event.get("name") for _key, event in bus.log_appends],+ )+ self.assertFalse(+ await bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ "claim-failed",+ ),+ )++ async def test_claim_written_before_drain_does_not_duplicate_turn(+ self,+ ) -> None:+ """Recovery consumes a still-present claimed head exactly once."""+ bus = _FakeBus()+ chat = _FakeChatService()+ dispatcher = WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ )+ await enqueue_chat_input(+ bus,+ "u",+ "claim-before-drain",+ "a",+ UserMsg("user", "once", id="once"),+ )+ pending = await bus.queue_read(+ MessageBusKeys.chat_inputs("claim-before-drain"),+ max_count=1,+ )+ payload = pending[0][1]+ await bus.registry_set(+ MessageBusKeys.chat_input_claim("claim-before-drain"),+ "claim",+ json.dumps({"state": "claimed", "payload": payload}),+ )++ self.assertTrue(+ await dispatcher._chat_queue.drain_chat_inputs(+ "u",+ "claim-before-drain",+ "a",+ ),+ )+ self.assertEqual(len(chat.calls), 1)+ self.assertEqual(+ await bus.queue_read(+ MessageBusKeys.chat_inputs("claim-before-drain"),+ max_count=1,+ ),+ [],+ )++ async def test_cancelled_started_turn_emits_terminal_event(self) -> None:+ """At-most-once cancellation is explicit rather than silent."""+ bus = _FakeBus()+ chat = _BlockingChatService(bus)+ registry = ChatRunRegistry()++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=registry,+ ):+ await enqueue_chat_input(+ bus,+ "u",+ "cancelled",+ "a",+ UserMsg("user", "interrupt me"),+ )+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)+ task = registry.get("cancelled")+ self.assertIsNotNone(task)+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ await _yield_a_few_times()++ event_names = [+ payload.get("name")+ for _key, payload in bus.log_appends+ if payload.get("name") is not None+ ]+ self.assertIn("chat_input_cancelled", event_names)+ self.assertEqual(+ await bus.queue_read(+ MessageBusKeys.chat_inputs("cancelled"),+ max_count=10,+ ),+ [],+ )++ async def test_cancel_event_failure_preserves_task_cancellation(+ self,+ ) -> None:+ """A broken event transport cannot replace ``CancelledError``."""++ class _FailingCancelledEventBus(_FakeBus):+ async def log_append(+ self,+ key: str,+ payload: dict,+ *,+ max_len: int | None = None,+ ttl_secs: int | None = None,+ ) -> str:+ if payload.get("name") == "chat_input_cancelled":+ raise RuntimeError("event transport unavailable")+ return await super().log_append(+ key,+ payload,+ max_len=max_len,+ ttl_secs=ttl_secs,+ )++ bus = _FailingCancelledEventBus()+ chat = _BlockingChatService(bus)+ registry = ChatRunRegistry()++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=registry,+ ):+ await enqueue_chat_input(+ bus,+ "u",+ "cancel-event-failure",+ "a",+ UserMsg("user", "interrupt me"),+ )+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)+ task = registry.get("cancel-event-failure")+ self.assertIsNotNone(task)+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ self.assertTrue(task.cancelled())+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."""@@ -484,18 +1036,321 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):UserConfirmResultEvent,)- async def test_wake_running_session_requeues_until_free(self) -> None:- """A ``wake`` whose target is still running is NOT dropped.+ async def test_pending_messages_can_change_during_current_reply(+ self,+ ) -> None:+ """Later turns remain editable and reorderable during generation."""+ bus = _FakeBus()+ chat = _BlockingChatService(bus)- Producers only enqueue one after finding no registered inbox- consumer, and a finishing run gives that registration up before- releasing its session lock — so a held lock is no evidence that- anything is still going to drain the inbox. Dropping here is- what used to strand a payload until the next user turn.- """+ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ first = UserMsg("user", "first", id="m1")+ second = UserMsg("user", "second", id="m2")+ third = UserMsg("user", "third", id="m3")++ await enqueue_chat_input(bus, "u", "s", "a", first)+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ second_item = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ second,+ )+ third_item = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ third,+ )+ await asyncio.sleep(0.05)+ self.assertEqual(len(chat.calls), 1)+ self.assertEqual(+ [item["id"] for item in await list_chat_inputs(bus, "s")],+ [second_item["id"], third_item["id"]],+ )++ await update_chat_input(+ bus,+ "u",+ "s",+ "a",+ second_item["id"],+ UserMsg("user", "second edited", id="m2"),+ )+ await reorder_chat_inputs(+ bus,+ "u",+ "s",+ "a",+ [third_item["id"], second_item["id"]],+ )+ chat.release_first.set()+ for _ in range(100):+ if len(chat.calls) == 3:+ break+ await asyncio.sleep(0.01)++ self.assertEqual(+ [call["input_msg"].id for call in chat.calls],+ ["m1", "m3", "m2"],+ )+ self.assertEqual(+ chat.calls[2]["input_msg"].content[0].text,+ "second edited",+ )+ self.assertEqual(+ await bus.queue_drain(+ MessageBusKeys.chat_inputs("s"),+ max_count=10,+ ),+ [],+ )+ self.assertFalse(+ await bus.registry_exists(+ MessageBusKeys.chat_input_pending_registry(),+ "s",+ ),+ )++ async def test_ordinary_message_waits_for_running_session(self) -> None:+ """A busy message trigger is dropped; the completing run's nudge+ advances the still-durable queue without periodic polling."""bus = _FakeBus()chat = _FakeChatService()- lock_key = MessageBus._SESSION_LOCK_KEY.format(sid="w2")+ lock_key = MessageBusKeys.session_lock("busy-message")+ bus._locks.add(lock_key)++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await enqueue_chat_input(+ bus,+ "u",+ "busy-message",+ "a",+ UserMsg("user", "later", id="queued"),+ )+ await asyncio.sleep(0.25)+ self.assertEqual(chat.calls, [])++ bus._locks.discard(lock_key)+ await enqueue_run_trigger(+ bus,+ user_id="u",+ session_id="busy-message",+ agent_id="a",+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(chat.calls[0]["input_msg"].id, "queued")++ async def test_pending_queue_index_survives_dispatcher_restart(+ self,+ ) -> None:+ """Busy-session recovery is durable, not an in-memory timer."""+ bus = _FakeBus()+ chat = _FakeChatService()+ lock_key = MessageBusKeys.session_lock("durable")+ bus._locks.add(lock_key)++ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await enqueue_chat_input(+ bus,+ "u",+ "durable",+ "a",+ UserMsg("user", "survive restart"),+ )+ await asyncio.sleep(0.05)++ self.assertTrue(+ await bus.registry_exists(+ MessageBusKeys.chat_input_pending_registry(),+ "durable",+ ),+ )++ bus._locks.discard(lock_key)+ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(+ chat.calls[0]["input_msg"].content[0].text,+ "survive restart",+ )++ async def test_fallback_continues_after_transient_failures(self) -> None:+ """Signal and recovery failures do not stop subsequent ticks."""+ for failure in ("publish", "recovery"):+ with self.subTest(failure=failure):+ bus = _FakeBus()+ dispatcher = WakeupDispatcher(+ bus,+ _FakeStorage(),+ _FakeChatService(),+ ChatRunRegistry(),+ )+ publish = AsyncMock(+ side_effect=[+ ConnectionError("signal")+ if failure == "publish"+ else None,+ None,+ ],+ )+ recovery = Mock(+ side_effect=[+ RuntimeError("schedule")+ if failure == "recovery"+ else None,+ None,+ ],+ )+ with (+ patch.object(bus, "publish", publish),+ patch.object(+ dispatcher._chat_queue,+ "schedule_recovery",+ recovery,+ ),+ patch(+ "agentscope.app._manager._wakeup_dispatcher."+ "asyncio.sleep",+ AsyncMock(+ side_effect=[+ None,+ None,+ asyncio.CancelledError(),+ ],+ ),+ ),+ ):+ with self.assertRaises(asyncio.CancelledError):+ await dispatcher._fallback_loop()+ self.assertEqual(+ publish.await_args_list,+ [mock_call(MessageBusKeys.wakeup_signal(), {})] * 2,+ )+ self.assertEqual(+ recovery.call_args_list,+ [mock_call(), mock_call()],+ )++ async def test_fallback_tick_drains_trigger_without_live_signal(+ self,+ ) -> None:+ """A lost pub/sub signal cannot strand a durable trigger forever."""+ bus = _FakeBus()+ chat = _FakeChatService()++ with patch(+ "agentscope.app._manager._wakeup_dispatcher."+ "_MESSAGE_FALLBACK_TICK_SECS",+ 0.01,+ ):+ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await bus.queue_push(+ MessageBusKeys.chat_inputs("tick"),+ {+ "id": "tick-item",+ "user_id": "u",+ "session_id": "tick",+ "agent_id": "a",+ "created_at": "2026-01-01T00:00:00Z",+ "input": UserMsg(+ "user",+ "lost signal",+ ).model_dump(mode="json"),+ },+ )+ await bus.registry_set(+ MessageBusKeys.chat_input_pending_registry(),+ "tick",+ '{"user_id": "u", "agent_id": "a"}',+ )+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(+ chat.calls[0]["input_msg"].content[0].text,+ "lost signal",+ )+ self.assertTrue(bus.wakeup_drain_task_names)+ self.assertEqual(+ set(bus.wakeup_drain_task_names),+ {"wakeup-dispatcher"},+ )++ async def test_ordinary_message_waits_for_hitl_resume(self) -> None:+ """Queued user turns stay behind a parked tool confirmation+ instead of being misinterpreted as its continuation."""+ bus = _FakeBus()+ chat = _FakeChatService()+ storage = _FakeStorage()+ storage.parked_session_ids.add("parked")++ async with WakeupDispatcher(+ message_bus=bus,+ storage=storage,+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await enqueue_chat_input(+ bus,+ "u",+ "parked",+ "a",+ UserMsg("user", "after confirmation", id="after-hitl"),+ )+ await asyncio.sleep(0.25)+ self.assertEqual(chat.calls, [])++ # Simulate the existing resume path completing the parked+ # reply, persisting a clean context tail and issuing its+ # completion nudge.+ storage.parked_session_ids.discard("parked")+ await enqueue_run_trigger(+ bus,+ user_id="u",+ session_id="parked",+ agent_id="a",+ kind=MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)++ self.assertEqual(chat.calls[0]["input_msg"].id, "after-hitl")++ async def test_wake_running_session_requeues_until_free(self) -> None:+ """A busy ``wake`` is retained until the inbox can be drained."""+ bus = _FakeBus()+ chat = _FakeChatService()+ lock_key = MessageBusKeys.session_lock("w2")bus._locks.add(lock_key)async with WakeupDispatcher(@@ -506,10 +1361,13 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):):await bus.queue_push(MessageBusKeys.wakeup_queue(),- {"user_id": "u", "session_id": "w2", "agent_id": "wa2"},+ {+ "user_id": "u",+ "session_id": "w2",+ "agent_id": "wa2",+ },)await bus.publish(MessageBusKeys.wakeup_signal(), {})-await asyncio.sleep(0.25)self.assertEqual(chat.calls, [])@@ -521,9 +1379,147 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):self.assertIsNone(chat.calls[0]["input_msg"])+class TestChatInputClaimReliability(IsolatedAsyncioTestCase):+ """Internal claim transitions favor correctness over UI latency."""++ async def test_transitions_outwait_foreground_mutation_timeout(+ self,+ ) -> None:+ """Claim state cannot fail merely because UI holds the lock."""++ class _SlowMutationLockBus(_FakeBus):+ @asynccontextmanager+ async def acquire_lock(+ self,+ key: str,+ *,+ ttl_secs: int = 600,+ ) -> AsyncGenerator[None, None]:+ del ttl_secs+ if key == MessageBusKeys.chat_input_mutation_lock("s"):+ await asyncio.sleep(0.02)+ yield++ bus = _SlowMutationLockBus()+ dispatcher = WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ )+ payload = {"id": "queued", "input": {}}++ with patch.object(+ MessageBusKeys,+ "CHAT_INPUT_MUTATION_TIMEOUT_SECS",+ 0.001,+ ):+ await dispatcher._chat_queue._set_chat_input_claim_state(+ "s",+ payload,+ "input_persisted",+ )+ self.assertTrue(+ await bus.registry_exists(+ MessageBusKeys.chat_input_claim("s"),+ "claim",+ ),+ )+ await dispatcher._chat_queue._finish_chat_input_claim("s")++ self.assertFalse(+ await bus.registry_exists(+ MessageBusKeys.chat_input_inflight_registry(),+ "s",+ ),+ )++class TestWakeupDispatcherLifecycle(IsolatedAsyncioTestCase):"""Tests covering the ``__aenter__`` / ``__aexit__`` ACM behaviour."""+ async def test_recovery_sweep_has_one_cluster_leader(self) -> None:+ """Two processes sharing a bus do not both run the O(N) sweep."""++ class _CountingQueue(ChatInputQueue):+ sweep_count = 0++ async def _recover_pending_chat_inputs_locked(self) -> int:+ type(self).sweep_count += 1+ return await super()._recover_pending_chat_inputs_locked()++ bus = _FakeBus()+ first = WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ )+ second = WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ )++ first._chat_queue = _CountingQueue(+ bus,+ _FakeStorage(),+ _FakeChatService(),+ )+ second._chat_queue = _CountingQueue(+ bus,+ _FakeStorage(),+ _FakeChatService(),+ )+ await asyncio.gather(+ first._chat_queue._recover_pending_chat_inputs(),+ second._chat_queue._recover_pending_chat_inputs(),+ )++ self.assertEqual(_CountingQueue.sweep_count, 1)+ self.assertEqual(+ bus._channel(MessageBusKeys.wakeup_signal()).qsize(),+ 0,+ )++ async def test_initial_recovery_does_not_block_startup(self) -> None:+ """An O(N) pending-session sweep runs outside ``__aenter__``."""++ class _SlowRecoveryBus(_FakeBus):+ def __init__(self) -> None:+ super().__init__()+ self.recovery_started = asyncio.Event()+ self.release_recovery = asyncio.Event()+ self._delay_recovery_once = True++ async def registry_getall(+ self,+ namespace: str,+ ) -> dict[str, str]:+ if (+ namespace == MessageBusKeys.chat_input_recovery_state()+ and self._delay_recovery_once+ ):+ self._delay_recovery_once = False+ self.recovery_started.set()+ await self.release_recovery.wait()+ return await super().registry_getall(namespace)++ bus = _SlowRecoveryBus()+ dispatcher = WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ )++ # pylint: disable=unnecessary-dunder-call+ await asyncio.wait_for(dispatcher.__aenter__(), timeout=0.2)+ await asyncio.wait_for(bus.recovery_started.wait(), timeout=0.2)+ bus.release_recovery.set()+ await dispatcher.__aexit__(None, None, None)+async def test_exit_cancels_loop_cleanly(self) -> None:"""``__aexit__`` cancels the dispatcher's loop task and returnswithout re-raising the cancellation."""@@ -545,3 +1541,616 @@ class TestWakeupDispatcherLifecycle(IsolatedAsyncioTestCase):self.assertIsNone(dispatcher._task)self.assertTrue(loop_task.cancelled() or loop_task.done())++ async def test_chat_service_strongly_retains_queue_nudge(self) -> None:+ """Detached nudge tasks stay referenced until completion."""+ bus = _FakeBus()+ service = object.__new__(ChatService)+ service._message_bus = bus+ service._queue_nudge_tasks = set()+ await bus.queue_push(+ MessageBusKeys.chat_inputs("s"),+ {"pending": True},+ )++ service.schedule_queue_nudge("u", "s", "a")+ self.assertEqual(len(service._queue_nudge_tasks), 1)+ await _yield_a_few_times()+ self.assertEqual(service._queue_nudge_tasks, set())+ triggers = await bus.queue_read(+ MessageBusKeys.wakeup_queue(),+ max_count=10,+ )+ self.assertEqual(+ triggers[0][1]["kind"],+ MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )+++class TestChatEndpointQueue(IsolatedAsyncioTestCase):+ """Ordinary HTTP chat inputs enter the FIFO instead of spawning."""++ async def test_user_message_is_accepted_into_session_fifo(self) -> None:+ """An ordinary POST is durably accepted instead of directly run."""+ bus = _FakeBus()+ chat_service = _FakeChatService()+ user_msg = UserMsg("user", "queued", id="http-message")++ response = await chat_endpoint(+ request=ChatRequest(+ agent_id="a",+ session_id="s",+ input=user_msg,+ ),+ user_id="u",+ storage=_FakeStorage(),+ chat_service=chat_service,+ chat_run_registry=ChatRunRegistry(),+ message_bus=bus,+ )++ self.assertEqual(response.status, "queued")+ self.assertEqual(chat_service.calls, [])+ queued = await bus.queue_drain(+ MessageBusKeys.chat_inputs("s"),+ max_count=10,+ )+ self.assertEqual(len(queued), 1)+ stored = await bus.registry_get(+ MessageBusKeys.chat_input_payloads("s"),+ queued[0][1]["input_ref"],+ )+ assert stored is not None+ self.assertEqual(json.loads(stored), user_msg.model_dump(mode="json"))++ triggers = await bus.queue_drain(+ MessageBusKeys.wakeup_queue(),+ max_count=10,+ )+ self.assertEqual(+ triggers[0][1]["kind"],+ MessageBusKeys.WAKEUP_KIND_QUEUED_MESSAGE,+ )++ async def test_cross_user_message_is_rejected_without_queue_damage(+ self,+ ) -> None:+ """POST /chat cannot inject into another user's session queue."""++ class _OwnerStorage(_FakeStorage):+ async def get_session(+ self,+ user_id: str,+ _agent_id: str,+ _session_id: str,+ ) -> object | None:+ return object() if user_id == "owner" else None++ bus = _FakeBus()+ existing = await enqueue_chat_input(+ bus,+ "owner",+ "shared-sid",+ "a",+ UserMsg("user", "keep me", id="existing"),+ )+ with self.assertRaises(HTTPException) as raised:+ await chat_endpoint(+ request=ChatRequest(+ agent_id="a",+ session_id="shared-sid",+ input=UserMsg("user", "inject", id="attack"),+ ),+ user_id="attacker",+ storage=_OwnerStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ message_bus=bus,+ )++ self.assertEqual(raised.exception.status_code, 404)+ self.assertEqual(+ [item["id"] for item in await list_chat_inputs(bus, "shared-sid")],+ [existing["id"]],+ )++ def test_empty_message_lists_are_rejected_by_request_schemas(+ self,+ ) -> None:+ """Neither enqueue nor PATCH can carry an empty Msg list."""+ with self.assertRaises(ValidationError):+ ChatRequest(agent_id="a", session_id="s", input=[])+ with self.assertRaises(ValidationError):+ UpdateChatQueueItemRequest(+ agent_id="a",+ session_id="s",+ input=[],+ )++ async def test_full_queue_returns_http_429(self) -> None:+ """POST /chat reports backpressure instead of growing forever."""+ bus = _FakeBus()+ with patch.object(MessageBusKeys, "CHAT_INPUT_MAX_LEN", 1):+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "already pending"),+ )+ with self.assertRaises(HTTPException) as raised:+ await chat_endpoint(+ request=ChatRequest(+ agent_id="a",+ session_id="s",+ input=UserMsg("user", "one too many"),+ ),+ user_id="u",+ storage=_FakeStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ message_bus=bus,+ )+ self.assertEqual(raised.exception.status_code, 429)++ async def test_queue_lock_timeout_returns_http_503(self) -> None:+ """POST /chat turns stale-lock waits into retryable backpressure."""+ for key in (+ MessageBusKeys.chat_input_mutation_lock("s"),+ MessageBusKeys.chat_input_user_quota_lock("u"),+ ):+ with self.subTest(key=key), patch.object(+ MessageBusKeys,+ "CHAT_INPUT_MUTATION_TIMEOUT_SECS",+ 0.01,+ ):+ async with InMemoryMessageBus() as bus:+ async with bus.acquire_lock(key):+ with self.assertRaises(HTTPException) as raised:+ await chat_endpoint(+ request=ChatRequest(+ agent_id="a",+ session_id="s",+ input=UserMsg("user", "retry later"),+ ),+ user_id="u",+ storage=_FakeStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ message_bus=bus,+ )+ self.assertEqual(raised.exception.status_code, 503)+ self.assertEqual(await list_chat_inputs(bus, "s"), [])+ self.assertEqual(+ await bus.registry_getall(+ MessageBusKeys.chat_input_pending_registry(),+ ),+ {},+ )++ async def test_slow_notification_keeps_http_acceptance(self) -> None:+ """Neither lock's wait deadline cancels an accepted queue write."""+ bus = _FakeBus()+ publish = bus.publish++ async def slow_publish(key: str, payload: dict) -> None:+ await asyncio.sleep(0.03)+ await publish(key, payload)++ message = UserMsg("user", "accepted")+ with patch.object(bus, "publish", slow_publish), patch.object(+ MessageBusKeys,+ "CHAT_INPUT_MUTATION_TIMEOUT_SECS",+ 0.01,+ ):+ response = await chat_endpoint(+ request=ChatRequest(+ agent_id="a",+ session_id="s",+ input=message,+ ),+ user_id="u",+ storage=_FakeStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ message_bus=bus,+ )+ items = await list_chat_inputs(bus, "s")+ self.assertEqual(+ response.model_dump(),+ {+ "status": "queued",+ "session_id": "s",+ "queue_item_id": items[0]["id"],+ },+ )+ self.assertEqual(+ items,+ [+ {+ "id": response.queue_item_id,+ "created_at": items[0]["created_at"],+ "input": message.model_dump(mode="json"),+ },+ ],+ )++ async def test_notification_failure_preserves_accepted_input(+ self,+ ) -> None:+ """Broadcast and wakeup failures leave accepted input recoverable."""+ for operation in (+ "_publish_chat_queue_changed",+ "enqueue_run_trigger",+ ):+ for error_type in (ConnectionError, TimeoutError):+ with self.subTest(operation=operation, error=error_type):+ bus = _FakeBus()+ message = UserMsg("user", "recover me")+ with patch.object(+ _bus_ops,+ operation,+ side_effect=error_type("offline"),+ ):+ response = await chat_endpoint(+ request=ChatRequest(+ agent_id="a",+ session_id="s",+ input=message,+ ),+ user_id="u",+ storage=_FakeStorage(),+ chat_service=_FakeChatService(),+ chat_run_registry=ChatRunRegistry(),+ message_bus=bus,+ )+ items = await list_chat_inputs(bus, "s")+ self.assertEqual(+ response.model_dump(),+ {+ "status": "queued",+ "session_id": "s",+ "queue_item_id": items[0]["id"],+ },+ )+ self.assertEqual(+ items,+ [+ {+ "id": response.queue_item_id,+ "created_at": items[0]["created_at"],+ "input": message.model_dump(mode="json"),+ },+ ],+ )+ # Remove any immediate trigger to exercise recovery.+ await bus.queue_delete(MessageBusKeys.wakeup_queue())+ chat = _FakeChatService()+ async with WakeupDispatcher(+ message_bus=bus,+ storage=_FakeStorage(),+ chat_service=chat,+ chat_run_registry=ChatRunRegistry(),+ ):+ await asyncio.wait_for(chat.notify.wait(), timeout=2)+ self.assertEqual(+ [call["input_msg"] for call in chat.calls],+ [message],+ )++ async def test_queue_write_failure_is_not_accepted(self) -> None:+ """Only post-acceptance notification errors may be suppressed."""+ bus = _FakeBus()+ error = ConnectionError("queue unavailable")+ with patch.object(bus, "queue_push", side_effect=error):+ with self.assertRaises(ConnectionError) as raised:+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "not accepted"),+ )+ self.assertIs(raised.exception, error)+ self.assertEqual(await list_chat_inputs(bus, "s"), [])++ async def test_body_timeout_is_not_reported_as_lock_contention(+ self,+ ) -> None:+ """Only lock acquisition timeouts become queue-busy errors."""+ async with InMemoryMessageBus() as bus:+ for lock, key in (+ (+ _bus_ops.chat_input_mutation(bus, "s"),+ MessageBusKeys.chat_input_mutation_lock("s"),+ ),+ (+ _bus_ops._chat_input_user_quota(bus, "u"),+ MessageBusKeys.chat_input_user_quota_lock("u"),+ ),+ ):+ with self.subTest(key=key):+ with self.assertRaisesRegex(TimeoutError, "body failed"):+ async with lock:+ raise TimeoutError("body failed")+ self.assertFalse(await bus.is_locked(key))+++class TestEditableChatQueue(IsolatedAsyncioTestCase):+ """Pending turns can be edited, deleted and reordered before start."""++ async def test_edit_delete_and_reorder_pending_turns(self) -> None:+ """All pending-item mutations preserve a consistent FIFO snapshot."""+ bus = _FakeBus()+ first = UserMsg("user", "first", id="q1")+ second = UserMsg("user", "second", id="q2")+ third = UserMsg("user", "third", id="q3")++ first_item = await enqueue_chat_input(bus, "u", "s", "a", first)+ second_item = await enqueue_chat_input(bus, "u", "s", "a", second)+ third_item = await enqueue_chat_input(bus, "u", "s", "a", third)++ edited = UserMsg("user", "second edited", id="q2")+ items = await update_chat_input(+ bus,+ "u",+ "s",+ "a",+ second_item["id"],+ edited,+ )+ self.assertEqual(+ items[1]["input"]["content"][0]["text"],+ "second edited",+ )++ items = await delete_chat_input(+ bus,+ "u",+ "s",+ "a",+ first_item["id"],+ )+ self.assertEqual(+ [item["id"] for item in items],+ [second_item["id"], third_item["id"]],+ )++ items = await reorder_chat_inputs(+ bus,+ "u",+ "s",+ "a",+ [third_item["id"], second_item["id"]],+ )+ self.assertEqual(+ [item["id"] for item in items],+ [third_item["id"], second_item["id"]],+ )+ self.assertEqual(+ [item["id"] for item in await list_chat_inputs(bus, "s")],+ [third_item["id"], second_item["id"]],+ )++ async def test_list_empty_queue_does_not_mutate_pending_registry(+ self,+ ) -> None:+ """The GET-style list operation is read-only."""+ bus = _FakeBus()+ await bus.registry_set(+ MessageBusKeys.chat_input_pending_registry(),+ "orphan-marker",+ '{"user_id": "u", "agent_id": "a"}',+ )++ self.assertEqual(await list_chat_inputs(bus, "orphan-marker"), [])+ self.assertTrue(+ await bus.registry_exists(+ MessageBusKeys.chat_input_pending_registry(),+ "orphan-marker",+ ),+ )++ async def test_started_turn_can_no_longer_be_changed(self) -> None:+ """An item disappears from management APIs once it is claimed."""+ bus = _FakeBus()+ item = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "starting", id="started"),+ )+ await bus.queue_drain(+ MessageBusKeys.chat_inputs("s"),+ max_count=1,+ )++ with self.assertRaises(LookupError):+ await delete_chat_input(bus, "u", "s", "a", item["id"])++ async def test_reorder_rejects_stale_snapshot(self) -> None:+ """Reorder requires an exact permutation of the latest snapshot."""+ bus = _FakeBus()+ first_item = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "one", id="one"),+ )+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "two", id="two"),+ )++ with self.assertRaises(ValueError):+ await reorder_chat_inputs(+ bus,+ "u",+ "s",+ "a",+ [first_item["id"]],+ )++ async def test_duplicate_message_ids_have_distinct_queue_ids(+ self,+ ) -> None:+ """Retries of one Msg.id remain independently reorderable."""+ bus = _FakeBus()+ msg = UserMsg("user", "retry me", id="same-message")+ first = await enqueue_chat_input(bus, "u", "s", "a", msg)+ second = await enqueue_chat_input(bus, "u", "s", "a", msg)++ self.assertNotEqual(first["id"], second["id"])+ items = await reorder_chat_inputs(+ bus,+ "u",+ "s",+ "a",+ [second["id"], first["id"]],+ )+ self.assertEqual(+ [item["id"] for item in items],+ [second["id"], first["id"]],+ )++ async def test_reorder_preserves_non_owned_payload_positions(self) -> None:+ """Defensive reorder never erases a foreign/corrupt queue item."""+ bus = _FakeBus()+ first = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "first"),+ )+ foreign = await enqueue_chat_input(+ bus,+ "other",+ "s",+ "a",+ UserMsg("user", "foreign"),+ )+ second = await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "second"),+ )++ await reorder_chat_inputs(+ bus,+ "u",+ "s",+ "a",+ [second["id"], first["id"]],+ )+ items = await list_chat_inputs(bus, "s")+ self.assertEqual(+ [item["id"] for item in items],+ [second["id"], foreign["id"], first["id"]],+ )++ async def test_enqueue_rejects_queue_over_capacity(self) -> None:+ """A bounded pending queue cannot grow without limit."""+ bus = _FakeBus()+ with patch.object(MessageBusKeys, "CHAT_INPUT_MAX_LEN", 2):+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "one"),+ )+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "two"),+ )+ with self.assertRaises(ChatQueueFullError):+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "three"),+ )++ async def test_enqueue_enforces_user_quota_across_sessions(self) -> None:+ """One user cannot multiply the queue cap with many sessions."""+ bus = _FakeBus()+ with patch.object(MessageBusKeys, "CHAT_INPUT_USER_MAX_LEN", 2):+ await enqueue_chat_input(+ bus,+ "u",+ "s1",+ "a",+ UserMsg("user", "one"),+ )+ await enqueue_chat_input(+ bus,+ "u",+ "s2",+ "a",+ UserMsg("user", "two"),+ )+ with self.assertRaises(ChatQueueFullError):+ await enqueue_chat_input(+ bus,+ "u",+ "s3",+ "a",+ UserMsg("user", "three"),+ )++ async def test_mutation_lock_wait_is_bounded(self) -> None:+ """A stale short lock surfaces retryable busy instead of hanging."""++ class _ContendedBus(_FakeBus):+ @asynccontextmanager+ async def acquire_lock(+ self,+ key: str,+ *,+ ttl_secs: int = 600,+ ) -> AsyncGenerator[None, None]:+ del ttl_secs+ if key == MessageBusKeys.chat_input_mutation_lock("s"):+ await asyncio.Event().wait()+ yield++ with patch.object(+ MessageBusKeys,+ "CHAT_INPUT_MUTATION_TIMEOUT_SECS",+ 0.01,+ ):+ with self.assertRaises(ChatQueueBusyError):+ await enqueue_chat_input(+ _ContendedBus(),+ "u",+ "s",+ "a",+ UserMsg("u", "queued"),+ )+ self.assertEqual(await list_chat_inputs(_ContendedBus(), "s"), [])++ async def test_queue_snapshots_are_not_written_to_replay_log(+ self,+ ) -> None:+ """Queue mutations fan out live; GET remains the durable source."""+ bus = _FakeBus()+ await enqueue_chat_input(+ bus,+ "u",+ "s",+ "a",+ UserMsg("user", "pending"),+ )+ self.assertEqual(bus.log_appends, [])diff --git a/tests/webrtc_audio_transport_test.py b/tests/webrtc_audio_transport_test.pyindex 0e2f9f5b2..b83a74a54 100644--- a/tests/webrtc_audio_transport_test.py+++ b/tests/webrtc_audio_transport_test.py@@ -30,7 +30,8 @@ from agentscope.app._service._webrtc_audio_transport import (WebRTCAudioTransport,)from agentscope.app._service._webrtc_session import WebRTCSession-from agentscope.app.message_bus import MessageBusKeys+from agentscope.app.message_bus import InMemoryMessageBus, MessageBusKeys+from agentscope.app._bus_ops import enqueue_chat_inputfrom agentscope.app.storage import CredentialRecord, RealtimeModelConfigfrom agentscope.event import (DataBlockDeltaEvent,@@ -1698,3 +1699,56 @@ class WebRTCSessionTest(unittest.IsolatedAsyncioTestCase):if __name__ == "__main__":unittest.main()+++class WebRTCQueueWakeupTest(unittest.IsolatedAsyncioTestCase):+ """Realtime lock release promptly makes ordinary queued input eligible."""++ async def test_nudge_follows_session_lock_release(self) -> None:+ """Closing voice queues a durable trigger without a recovery tick."""+ async with InMemoryMessageBus() as bus:+ await enqueue_chat_input(+ bus,+ "alice",+ "session-1",+ "agent-1",+ UserMsg("u", "next"),+ )+ await bus.queue_drain(MessageBusKeys.wakeup_queue())+ original_push = bus.queue_push++ async def checked_push(key: str, payload: dict) -> str:+ self.assertFalse(+ await bus.is_locked(+ MessageBusKeys.session_lock("session-1"),+ ),+ )+ return await original_push(key, payload)++ session = _make_session(+ agent_factory=AsyncMock(+ return_value=_FakeAgent(+ {"id": "voice", "role": "assistant"},+ [],+ ),+ ),+ storage=_FakeStorage(),+ message_bus=bus,+ on_closed=lambda _: None,+ )+ with patch.object(bus, "queue_push", checked_push):+ await session._run()+ triggers = await bus.queue_drain(MessageBusKeys.wakeup_queue())+ self.assertEqual(+ [payload for _, payload in triggers],+ [+ {+ "user_id": "alice",+ "session_id": "session-1",+ "agent_id": "agent-1",+ "kind": "queued_message",+ "input": None,+ },+ ],+ )+ self.assertEqual(session.transport.errors, [])