Skip to content

fix(agents): strip trailing assistant messages after sessions_yield artifact removal - #113190

Merged
obviyus merged 4 commits into
openclaw:mainfrom
SunnyShu0925:fix/sessions-yield-trailing-assistant-109638
Jul 27, 2026
Merged

obviyus merged 4 commits into
openclaw:mainfrom
SunnyShu0925:fix/sessions-yield-trailing-assistant-109638

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

After sessions_yield, the yielded session transcript can end with an assistant role when the agent performed tool work between sessions_spawn and sessions_yield, causing subagent completion auto-announce to permanently deadlock with "Cannot continue from message role: assistant".

  • Problem: stripSessionsYieldArtifacts() removes yield-specific artifacts (aborted assistant + interrupt custom message) but leaves trailing regular assistant messages from pre-yield tool work. When subagent auto-announce calls agentLoopContinue(), the role-continuity check (lastMessage.role === "assistant" at agent-loop.ts:158) throws TranscriptNotContinuableError, permanently blocking the yielded session.
  • Solution: Add a second cleanup pass (Phase 2) that strips trailing regular assistant messages after Phase 1, and synchronize persisted session state using a count-capped predicate derived from the active suffix removal count — never exceeding what was removed in-memory.
  • What changed: src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts (Phase 2 while-loop + count-capped persisted cleanup), src/agents/embedded-agent-runner/run/attempt.sessions-yield.test.ts (9 new unit tests)
  • What did NOT change: Non-yield sessions, immediate-yield path (spawn→yield with no intervening tool work), agentLoopContinue() role check, subagent-announce-delivery.ts logic

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Motivation

The current stripSessionsYieldArtifacts removes only the yield-specific entries (aborted assistant + interrupt custom message). When the agent called tools between spawn and yield, those pre-yield tool calls generated assistant messages at the end of the transcript. After yield, subagent auto-announce fails because agentLoopContinue checks lastMessage.role === "assistant". This permanently blocks the yielded session until manual sessions_send intervention.

The fix makes the transcript cleanup complete: after removing yield artifacts, also strip trailing regular assistant messages so the transcript ends with a tool_result role that allows continuation injection.

Evidence

  • Behavior addressed: sessions_yield transcript cleanup leaves trailing regular assistant messages, causing subagent auto-announce deadlock with "Cannot continue from message role: assistant"

  • Real environment tested: Linux x64 (Co-Claw), Node v22.22.3, Model: zte/Qwen3-235B-A22B, commit 84df4a2eaf1, branch fix/sessions-yield-trailing-assistant-109638, real OpenClaw embedded agent mode

  • Exact steps or command run after this patch:

    # E2E: real model inference (Qwen3-235B-A22B), spawn→tools→yield→subagent→complete
    OPENCLAW_HOME=/tmp/openclaw-dev-109638 \
    node scripts/run-node.mjs agent --agent main --local --json \
      -m "spawn一个subagent,做一次curl工具调用,然后yield等subagent返回"
    
    # Unit tests
    node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt.sessions-yield.test.ts --run
    node scripts/run-vitest.mjs src/agents/embedded-agent-runner/sessions-yield.orchestration.test.ts --run
    
  • Evidence after fix:

    E2E yield→subagent→auto-announce (real model, Qwen3-235B-A22B):

    # Yield completed with end_turn — NOT blocked:
    "yielded": true, "stopReason": "end_turn"
    
    # Subagent work (curl) executed successfully after yield:
    ✅ curl执行完成
    {"args": {}, "headers": {"Host": "httpbin.org",
     "User-Agent": "curl/7.61.1"}, "origin": "160.30.148.33"}
    
    # Session completed without deadlock: stopReason=stop
    

    Transcript state matrix (before vs after fix):

    Scenario Before strip (last msg) After strip (last msg) Auto-announce
    spawn → yield (no tool work) tool_result tool_result Succeeds (unchanged)
    spawn → tools → yield assistant(work) tool_result (fixed) Succeeds (new)
    spawn → multiple tools → yield assistant(work2) tool_result (fixed) Succeeds (new)

    Unit tests (25 total, no regression):

    ✓ attempt.sessions-yield.test.ts — 9 new (Phase 1/2, type guard, count cap, preserveTrailing)
    ✓ sessions-yield.orchestration.test.ts — 9 existing (no regression)
    ✓ attempt-prompt-error.test.ts — 4 (stripSessionsYieldArtifacts callers)
    ✓ attempt-phase-lifecycle.test.ts — 3 (removeTrailingEntries callers)
    

    Persisted cleanup comparison vs PR fix(agents): strip trailing assistant messages after sessions_yield artifact removal #109806:

    Scenario PR fix(agents): strip trailing assistant messages after sessions_yield artifact removal #109806 (isTrailingAssistant) This PR (count-capped)
    Active suffix removes 3, persisted has 5 assistants Removes all 5 ❌ over-deletes Removes exactly 3 ✅
    Divergent active vs persisted state Over-deletes persisted-only entries Stops at removedCount cap ✅
    Extra custom/label entries Preserved (same) Preserved (same)
  • Observed result after fix:

    1. E2E yield→auto-announce completes with stopReason=end_turn (no deadlock); subagent curl executes successfully
    2. All 9 new unit tests pass (Phase 1/2, type guard, count cap, preserveTrailing, no-op)
    3. All 16 existing orchestration/error/phase tests pass without regression
    4. No new lint errors, zero as any casts (type-suppression inventory clean)
  • What was not tested: None — the E2E test covers the full spawn→tools→yield→subagent→complete cycle with real model inference

Root Cause

stripSessionsYieldArtifacts() was introduced with only yield-specific artifact removal (aborted assistant + interrupt custom message). It did not account for trailing regular assistant messages generated by pre-yield tool calls. After yield, agentLoopContinue() (agent-loop.ts:158) checks lastMessage.role === "assistant" and throws TranscriptNotContinuableError.

Regression Test Plan

Existing tests cover all non-yield and simple-yield paths. The fix adds no new branches outside the yield handler. All 25 related tests pass.

User-visible / Behavior Changes

Sessions that previously deadlocked after yield→subagent→auto-announce will now complete successfully.

Security Impact

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Best-fix Verdict

  • Best fix: Yes — the fix repairs the transcript invariant at the source without weakening the role-continuity check.
  • Refactor needed: No — focused 2-phase cleanup within the existing function boundary.
  • Alternative considered: (1) Weaken agentLoopContinue role check — invariant protects all continuation paths. (2) Independent isTrailingAssistant predicate for persisted cleanup — over-deletes when persisted transcript diverges from active view (P1 finding on PR fix(agents): strip trailing assistant messages after sessions_yield artifact removal #109806).

AI Assistance

  • AI-assisted: Yes
  • Co-Authored-By: Claude [email protected]
  • Human confirmed understanding of code changes: Yes

Risks and Mitigations

  • Highest risk: Persisted session cleanup could over-delete entries if predicate is broader than active suffix removal.
  • Mitigation: Count-capped predicate removes at most removedCount entries of removable types only; preserveTrailing protects custom/label/session_info.
  • Compatibility: None — only changes behavior in the yield abort handler.

Fixes #109638

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jul 24, 2026
@SunnyShu0925
SunnyShu0925 force-pushed the fix/sessions-yield-trailing-assistant-109638 branch from 93b8170 to 947151b Compare July 24, 2026 01:31
@SunnyShu0925
SunnyShu0925 force-pushed the fix/sessions-yield-trailing-assistant-109638 branch 2 times, most recently from 947151b to 84df4a2 Compare July 24, 2026 02:56
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 High-priority user-facing bug, regression, or broken workflow. labels Jul 25, 2026
@clawsweeper

clawsweeper Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 25, 2026, 6:19 AM ET / 10:19 UTC.

ClawSweeper review

What this changes

This PR extends yielded-session cleanup to remove trailing regular assistant transcript messages and caps the matching persisted-session removals so subagent completion can resume the parent session.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

Keep this PR open for normal merge review. Current main still removes only the synthetic yield-abort artifacts, while this branch also removes the trailing assistant suffix that blocks continuation; the branch’s count-capped persistence cleanup is a materially safer candidate than the overlapping open PR at #109806. Likely related people: samrrr (high confidence as the production reporter) and kagura-agent (medium confidence as the author of the overlapping alternative implementation).

Priority: P1
Reviewed head: 723009d956c96e04e466c899638711e26e016574

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, evidence-backed bug fix with green checks and a credible real-run result; it needs ordinary maintainer review rather than a repair loop.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body supplies a concrete real embedded-agent command and after-fix yield-to-subagent-completion output; it also identifies the tested environment and redacts no sensitive values beyond an ordinary public endpoint result.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body supplies a concrete real embedded-agent command and after-fix yield-to-subagent-completion output; it also identifies the tested environment and redacts no sensitive values beyond an ordinary public endpoint result.
Evidence reviewed 5 items Current-main behavior remains incomplete: Current main removes only aborted assistant and yield-interrupt entries in stripSessionsYieldArtifacts; it does not remove ordinary trailing assistant messages before attempting persisted cleanup.
PR changes the correct cleanup boundary: The proposed branch adds a second suffix-removal phase for regular assistant entries and derives persisted removal from the active removal count, avoiding the broader independent predicate used by the overlapping proposal.
Continuation entry point uses the yield cleanup path: The embedded attempt wires sessions_yield to queue the interrupt and abort the active session; the cleanup helper is therefore the bounded place to restore a continuable transcript state rather than weakening the general continuation invariant.
Findings None None.
Security None None.

How this fits together

The embedded agent runner turns sessions_yield into an intentional abort, then removes temporary transcript artifacts before a child agent’s completion is delivered back to the parent. The cleaned live and persisted transcript tails must leave a continuable role so the next agent turn can be injected safely.

flowchart TD
  A[Parent agent transcript] --> B[sessions_yield]
  B --> C[Yield abort cleanup]
  C --> D[Live transcript tail]
  C --> E[Persisted transcript entries]
  D --> F[Subagent completion delivery]
  E --> F
  F --> G[Parent continuation turn]
Loading

Before merge

  • Complete next step (P2) - No discrete defect in the submitted patch requires a ClawSweeper repair; this is ready for normal human merge review of the current head.
Agent review details

Security

None.

PR surface

Source +26, Tests +260. Total +286 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 70 44 +26
Tests 1 260 0 +260
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 330 44 +286

Review metrics

None.

Technical review

Best possible solution:

Land one focused fix for the canonical deadlock: retain the two-phase live cleanup and count-capped persisted cleanup, with the accompanying regression coverage, rather than merging two competing implementations of the same transcript invariant.

Do we have a high-confidence way to reproduce the issue?

No direct current-main run was performed in this read-only review, but the failure path is high-confidence from current source plus the production transcript evidence in #109638.

Is this the best way to solve the issue?

Yes. Repairing the yield-specific transcript cleanup preserves the general continuation role check and is narrower than weakening continuation behavior globally.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against faaab9bd4819.

Labels

Label changes:

  • add P1: The targeted bug can permanently block a normal subagent-completion workflow until manual intervention, while the fix remains bounded to yielded-session cleanup.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies a concrete real embedded-agent command and after-fix yield-to-subagent-completion output; it also identifies the tested environment and redacts no sensitive values beyond an ordinary public endpoint result.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body supplies a concrete real embedded-agent command and after-fix yield-to-subagent-completion output; it also identifies the tested environment and redacts no sensitive values beyond an ordinary public endpoint result.

Label justifications:

  • P1: The targeted bug can permanently block a normal subagent-completion workflow until manual intervention, while the fix remains bounded to yielded-session cleanup.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body supplies a concrete real embedded-agent command and after-fix yield-to-subagent-completion output; it also identifies the tested environment and redacts no sensitive values beyond an ordinary public endpoint result.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies a concrete real embedded-agent command and after-fix yield-to-subagent-completion output; it also identifies the tested environment and redacts no sensitive values beyond an ordinary public endpoint result.

Evidence

What I checked:

Likely related people:

  • samrrr: Reported the concrete deadlock, affected transcript shape, and production terminal outcome tracked by the canonical bug. (role: production reporter; confidence: high; files: src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts)
  • kagura-agent: Authored the earlier open implementation for the same cleanup invariant; its persistence approach is the specific alternative this PR improves on. (role: adjacent implementation author; confidence: medium; commits: 2c9874ba176f; files: src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@obviyus obviyus self-assigned this Jul 27, 2026
SunnyShu0925 and others added 4 commits July 28, 2026 00:25
…eld artifact removal

After sessions_yield, stripSessionsYieldArtifacts removes yield-specific
artifacts (aborted assistant + interrupt custom message) but leaves trailing
regular assistant messages from pre-yield tool work intact. When a subagent
completes and auto-announce tries to inject a continuation turn, the gateway
rejects it because the last visible message role is "assistant", causing a
permanent deadlock (terminal_outcome=blocked).

Changes in attempt.sessions-yield.ts:
- Phase 1 (existing): remove aborted assistant + interrupt custom message
- Phase 2 (new): remove trailing regular assistant messages from pre-yield work
- Persisted cleanup: use count-capped type-checking predicate derived from
  active suffix removal count, never exceeding what was removed in-memory

Unlike the competing approach (independent isTrailingAssistant predicate),
the count-capped predicate prevents over-deletion when persisted transcript
state diverges from the active session view.

Tests: attempt.sessions-yield.test.ts (9 new: Phase 1/Phase 2, type guard,
       count cap, preserveTrailing, no-op scenarios),
       sessions-yield.orchestration.test.ts (9 passed),
       attempt-prompt-error.test.ts (4 passed),
       attempt-phase-lifecycle.test.ts (3 passed)

Co-Authored-By: Claude <[email protected]>

Fixes openclaw#109638
Fix two CI failures in PR openclaw#113190:

1. check-test-types: Resolve TypeScript errors in test file
   - TS2352: Use  for type conversions
   - TS18046: Type predicate parameters with RemoveTrailingPredicate
   - TS2339: Type options parameter with RemoveTrailingOptions

2. check-lint: Apply oxfmt formatting to both files
   - Reorder imports (type imports first)
   - Fix multi-line formatting for long expressions

Co-Authored-By: Claude <[email protected]>
@obviyus
obviyus force-pushed the fix/sessions-yield-trailing-assistant-109638 branch from e928399 to 5ff86bd Compare July 27, 2026 22:29
@obviyus
obviyus merged commit eeeae78 into openclaw:main Jul 27, 2026
111 of 115 checks passed
@obviyus

obviyus commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Landed via squash onto main.

  • Proof: contributor live E2E plus repository real-behavior proof; exact-head CI was 17 passed, 0 failed at merge, with only non-required jobs pending
  • Maintainer validation: targeted formatting check, git diff --check, and final autoreview clean
  • Changelog: release-note context captured in the PR body and merge commit; no CHANGELOG.md change
  • Land commit: 5ff86bd843e75cbbf0aeec890f2233ab03fbeb2c
  • Merge commit: eeeae78bccb13509a3189f3c13b036defb2f02a9

Thanks @SunnyShu0925!

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 28, 2026
* [AI] fix(agents): strip trailing assistant messages after sessions_yield artifact removal
* fix(ci): resolve check-lint and check-test-types failures
* fix(agents): simplify sessions_yield cleanup (openclaw#113190)
* fix(agents): separate sessions_yield cleanup budgets (openclaw#113190) (thanks @SunnyShu0925)

---------

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: sessions_yield deadlock — auto-announce fails with "Cannot continue from message role: assistant" when work is done between spawn and yield

2 participants