Skip to content

fix(pipeline): preserve media/reply follow-ups and strict turn ordering - #11322

Open
JosephTian876 wants to merge 1 commit into
AstrBotDevs:masterfrom
JosephTian876:fix/follow-up-preserve-media-and-order
Open

JosephTian876 wants to merge 1 commit into
AstrBotDevs:masterfrom
JosephTian876:fix/follow-up-preserve-media-and-order

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

When a user sends a follow-up message while an agent turn is still running (thinking or executing tools), try_capture_follow_up() offers the raw platform event to AgentTurn.steer(), where NativeAgentSession.steer_turn() extracts text via input.event.get_message_str() or input.event.get_message_outline().

This causes three user-facing bugs:

  1. Silent loss of media attachments:
    • A pure image message (Image with empty message_str) falls back to get_message_outline(), collapsing the image into the literal 4-character string "[图片]" and consuming the event before it can reach multimodal request preparation, image encoding, or image captioning. The model sees only "[图片]" and cannot inspect the image.
    • Mixed text + media messages (Image, Record without STT transcription, Video, File) keep only message_str and silently drop the attached media components.
  2. Silent loss of quoted reply context and structured inputs:
    • A message containing a Reply component either drops the quoted message entirely (when comment text is present, get_message_str() is non-empty so Reply is ignored) or degrades to a shallow outline without running async quoted-text/image extraction (extract_quoted_message_text / extract_quoted_message_images).
    • Events carrying explicit provider_request, side-thread thread_selected_text, or structured wakeup tool_result payloads would likewise lose those fields if collapsed into text-only steering.
  3. Message reordering when bypassing plain-text steering:
    • Simply skipping steering for a media/reply message (Msg 2) while Run 1 is still active is insufficient: if the user immediately sends a plain-text message (Msg 3, e.g. "look at the image I just sent") before Run 1 finishes, Msg 3 would steer Run 1 and jump ahead of Msg 2.

Modifications

  • Shared plain-text steering predicate (astrbot/core/agent_input.py):

    • Added extract_plain_steering_text(event) returning the original message text (preserving whitespace) only when the event contains no non-plain input components (Image, File, Record, Video, Reply) and no structured extras (provider_request, non-empty thread_selected_text, or wakeup tool_result).
    • Plain text messages (including group messages with At / Face or voice messages already transcribed to Plain by PreProcessStage STT) continue to steer normally; get_message_outline() is never used to fabricate placeholder text for media/replies.
  • Runtime steering defense-in-depth (astrbot/core/astr_agent_runtime/session.py):

    • Updated NativeAgentSession.steer_turn() so raw-event steering (input.content is None) delegates to extract_plain_steering_text(input.event) and rejects non-plain events instead of falling back to get_message_outline().
    • Explicit portable steering (input.content is not None, used by SDK AgentRun.steer() and subagent delivery) keeps its documented format_input_content() contract unchanged.
  • Strict arrival-order barrier and leak-free cleanup (astrbot/core/pipeline/process_stage/follow_up.py, astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py):

    • Replaced untyped order-state dicts with typed _FollowUpOrderSlot and _FollowUpOrderState dataclasses, and allowed FollowUpCapture to represent deferred (non-steered) captures (receipt=None, monitor_task=None).
    • When a non-steerable message arrives during an active turn (or while an earlier deferred/unconsumed turn or session.pending_turn_count is waiting), try_capture_follow_up() skips turn.steer() and reserves a deferred order slot. Subsequent plain-text messages observe the barrier and queue strictly in arrival order instead of steering ahead of the deferred turn.
    • Once the deferred event itself becomes the active turn (matched by owner event identity) with no further slots queued behind it, plain-text steering works normally on that turn.
    • Hardened finalize_follow_up_capture() with try...finally around monitor-task cancellation so order slots are always released and downstream waiters woken on early returns, exceptions, or cancellations without leaking _FOLLOW_UP_ORDER_STATE.
    • Added a post-wait stop check in InternalAgentSubStage.process() so queued events stopped via /stop or /reset while waiting exit cleanly without emitting spurious typing indicators or starting new runs.
  • Tests (tests/unit/test_follow_up_media_and_order.py):

    • Added 35 unit and end-to-end integration tests covering pure/mixed Image, Record, Video, File, Reply (media, plain-text, and reply-id-only), structured extras, At/Face/STT plain-text preservation, NativeAgentSession.steer_turn() defense-in-depth, FIFO plain-text steering regression, image-then-text anti-reordering, barrier release when the deferred turn becomes active, transition-gap and pending_turn_count races, mid-queue/out-of-order cancellations, monitor errors, /stop cleanup, and zero state leakage.
  • This is NOT a breaking change. / 这不是一个破坏性变更。

Verification Steps & Test Results

ruff check .
ruff format --check .
git diff --check
pytest tests/unit/test_follow_up_media_and_order.py tests/unit/test_agent_runtime.py tests/unit/test_wakeup_pipeline.py tests/unit/test_webchat_follow_up_status.py tests/test_tool_loop_agent_runner.py tests/unit/subagent/ tests/test_process_stage_images.py tests/unit/test_astr_main_agent.py -q
  • ruff check .: All checks passed!
  • ruff format --check .: 599 files already formatted
  • git diff --check: clean
  • pytest: 584 passed (including all 35 new unit/end-to-end tests in tests/unit/test_follow_up_media_and_order.py and all existing runtime, wakeup, webchat follow-up, tool-loop runner, subagent, process-stage image, and main-agent suites).

Backport Compatibility Note (v4.29.4)

The same design maps directly onto v4.29.4, where active runs are tracked via _ACTIVE_AGENT_RUNNERS[umo] (runner.run_context.context.event as the owner event) in astrbot/core/pipeline/process_stage/follow_up.py, follow-up text extraction lives in _event_follow_up_text(), and InternalAgentSubStage lives in astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py.

Suggested Merge Order


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。

  • 📚 I checked the affected WebUI instructions and screenshots in docs/zh and docs/en against the changed navigation, page structure, and labels, and updated them in this PR (or explained why no documentation update is needed). For renamed, moved, or merged entry points, I included an old entry → new entry mapping in the documentation and changelog.
    / 我已对照变化后的 WebUI 入口、页面结构和术语,核对并在本 PR 中更新 docs/zh 和 docs/en 的相关操作说明与截图(或说明无需更新文档的原因)。No WebUI navigation, page structure, or user-facing labels were changed.

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txt 和 pyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

Summary by Sourcery

Preserve rich follow-up inputs and enforce FIFO processing while maintaining plain-text steering for eligible messages.

Bug Fixes:

  • Preserve media attachments, quoted replies, and structured follow-up inputs by routing them through full turn processing instead of text-only steering.
  • Prevent later plain-text follow-ups from overtaking deferred media or reply messages by enforcing strict arrival ordering.
  • Ensure stopped or cancelled deferred follow-ups release ordering state without starting unnecessary runs or typing indicators.

Enhancements:

  • Centralize plain-text steering eligibility checks and retain defense-in-depth validation in native agent sessions.

Tests:

  • Add comprehensive unit and end-to-end coverage for media, replies, structured inputs, ordering barriers, cancellation, stop handling, and cleanup.

@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Sorry @JosephTian876, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 5 days and 16 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 97.24138% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
astrbot/core/pipeline/process_stage/follow_up.py 98.21% 2 Missing ⚠️
.../process_stage/method/agent_sub_stages/internal.py 66.66% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@JosephTian876
JosephTian876 force-pushed the fix/follow-up-preserve-media-and-order branch from d5fe9f8 to a21bbcb Compare November 27, 2026 02:29

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery assessment

Approved.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants