Skip to content

fix(gateway): the turn after a subagent completion misses the prompt cache - #181673

Merged
steipete merged 2 commits into
openclaw:mainfrom
masatohoshino:fix/announce-prompt-persistence
Oct 26, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
masatohoshino:fix/announce-prompt-persistence

Conversation

@masatohoshino

@masatohoshino masatohoshino commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Closes #181672

Related: #150081
Related: #151962

What Problem This Solves

Fixes: when a subagent completes while its requester is idle, the completion turn's user message reaches the model but is never saved, so the next owner turn replays a different history and misses the prompt cache from that point.

User Impact

User impact: after a subagent completion, the next turn reuses the cached prefix through the completion turn, and the stored history keeps the completion turn whole instead of a runtime-context message with no turn before it. Chat history does not change: the completion's user message stays hidden.

Why This Change Was Made

The Gateway agent method suppressed prompt persistence for subagent completion handoffs (shouldSuppressAgentPromptPersistence). #79618 added it so the handoff prompt ([Inter-session message] … sourceTool=subagent_announce) would neither show in WebChat and chat.history nor be written to the raw transcript. This PR deliberately brings back the transcript row and keeps the display part: the row is saved with display: false and its inter_session / subagent_announce provenance, chat display hides such rows by provenance, and the older row filter from that PR stays. Since then the runtime context travels in a separate hidden carrier saved right after this turn, and the transcript hygiene rules (#137273) keep hidden internal input in model history so replay keeps the request prefix. Without the user turn, the saved carrier has no turn before it.

The completion turn now takes the existing persistence path that subagent settle wakes (subagent_settle) and private completions already use: the user turn is saved with display: false and its provenance, and, like those turns, it is durably admitted before it runs. The unused helper is removed.

Evidence

Tested at e1201d7891e (base upstream/main 53f8d4f7f57). The Gateway runs below are at 1bab55aad8d; the later commit changes tests only.

Real Gateway: the built Gateway on each side, in an isolated HOME and state directory with the network off and a synthetic token, a local recording OpenAI-compatible Chat Completions provider, and a local IRC server. The owner sends 9 direct messages; turns 4 and 7 make the agent spawn a subagent, and each completion runs a parent turn through the Gateway agent method. Each parent request's message history (system prompt ignored, subagent requests skipped) is compared with the previous parent request's. msg[i] indexes the request's messages, counting the system message as 0; lostTok is the history not reused, estimated as characters / 4.

Before (base 53f8d4f7f57):

n   step  histMsgs prevMsgs shared prefixOk firstDiff     lostTok
7   2     16       13       13     true                   0
8   3     18       16       14     false    msg[15]:user  899
13  5     29       26       26     true                   0
14  6     31       29       27     false    msg[28]:user  994
history breaks=2 lostTok=1893
(the other 9 parent requests: request 1 has no previous request; 8 extend the previous one)

After (this PR):

n   step  histMsgs prevMsgs shared prefixOk firstDiff     lostTok
7   2     16       13       13     true                   0
8   3     19       16       16     true                   0
13  5     30       27       27     true                   0
14  6     33       30       30     true                   0
history breaks=0 lostTok=0
(the other 9 parent requests: request 1 has no previous request; 8 extend the previous one)

Observed result: on the base, request 8 continues with the completion's runtime context at msg[15] because the completion's user message was never stored (same at request 14); 2 of the 12 parent requests that follow another miss the prefix. With this PR the stored transcript has a hidden user row (display: false, inter_session / subagent_announce) before the runtime-context entry, and all 12 extend the previous request. chat.history for the session after the run returns 28 messages on both sides with the same role and content for each (ids, including child session keys, and timestamps normalized; metadata such as sequence numbers and usage not compared); neither shows the completion's user message.

With #180608 merged locally on top, all 12 parent requests that follow another also keep the system prompt and tools unchanged, so the whole request extends the previous one. This PR does not depend on it.

Regression test: src/gateway/agent-turn/agent-run-settle-continuation.native.test.ts prepares a subagent completion handoff (subagent_announce provenance, task_completion event) through prepareAgentRunUserTurn with the real transcript recorder and session store, persists it, and reads the stored transcript: one user row with display: false and the handoff's provenance. On the base it fails (expected prepared recorder to be defined: the prompt is suppressed, so no recorder exists); with this PR it passes. The other 16 tests in the file pass on both. It replaces the test from #79618 in agent.media-and-routing.test-utils.ts, which asserted the suppression on the mocked command call; its remaining checks (model state preserved for internal callers, the inter-session message header) are covered by sibling tests there.

Checks: pnpm test <file> --maxWorkers=1 for both changed test files, the src/gateway/agent-turn tests and the Gateway suites that cover subagent_announce sessions, history and display; tsgo core and the gateway-methods and gateway-other test projects; oxfmt --check and oxlint on the changed files. The broad suites run in this PR's CI. The red auto-response check is the Barnacle workflow failing with TypeError: Cannot read properties of undefined (reading 'owner') in scripts/github/barnacle-auto-response.mjs; the same failure appears on unrelated PRs and issues at the same time (for example https://github.com/openclaw/openclaw/actions/runs/39968677427), so it is not caused by this change.

Test file --maxWorkers=1 wall CI seconds
src/gateway/agent-turn/agent-run-settle-continuation.native.test.ts 19 s (17 tests) new case 0.94 s in checks-node-changed-compact-large-15 (job)
src/gateway/server-methods/agent.test.ts (loads agent.media-and-routing.test-utils.ts) 50 s (410 tests) no new case (one test removed)

Simplify pass: removes shouldSuppressAgentPromptPersistence and its three imports; the suppression requested explicitly by callers stays. Against the merge base: production +2/−27, tests +42/−48 (one test moved to the owner suite, no new test file).

Not covered: real provider cache counters (the local provider reports none; the claim is about request prefixes), CLI-backend requesters, restart recovery of a completion turn, the live Control UI view during the turn (only chat.history after the run was compared), and private completions (unchanged; they already saved their turn).

The Gateway agent turn skipped persisting the user turn of a subagent completion handoff, while the turn's hidden runtime context was still saved after it. The next request then replayed a different history and lost the prompt cache. Persist the turn through the existing path with its inter_session provenance and display: false, as the steering path already does, and remove the unused helper.
@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Oct 23, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Persist subagent completion prompts as hidden transcript turns so subsequent model requests preserve their history prefix.

Example: An idle parent receives a subagent completion, then its owner sends another message.

  • Before: In the supplied Gateway trace, request 8 omits the completion user message at messages[15], breaking prefix reuse.
  • After: Request 8 retains all 16 preceding history messages, while visible chat history remains unchanged.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A small, approved repair with shipped-entry-point evidence, a meaningful persistence regression, passing exact-head CI gates, and no remaining findings; existing hidden-row formats require no migration.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied built-Gateway traces exercise IRC input, real agent/subagent execution, the Gateway completion method, transcript persistence, and a recording local provider; history-prefix breaks fall from 2 to 0 while chat.history remains unchanged. The production proof predates only the test-only final commit and establishes request-prefix continuity rather than provider cache counters.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: The turn after an idle-parent subagent completion resends part of the conversation without reusable cached history.
Reason: The focused repair restores stable model history, preserves visible chat behavior, and has explicit approval for the intentional raw-transcript retention change.

Merge readiness

✅ Ready for maintainer review

Keep open for landing: this PR fixes a remaining history-prefix defect, and Peter’s explicit approval resolves the previous review’s retention-policy blocker. No actionable patch defects remain.

Priority: P2
Reviewed head: e1201d7891e1228e46878892853ed13817d89606

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Gateway agent-turn owner admits completion input into the existing transcript recorder; model replay consumes the stored turn, while chat projection hides internal completion messages.

flowchart LR
  A[Subagent completion] --> B[Gateway agent turn]
  B --> C[Existing transcript recorder]
  C --> D[Hidden transcript turn]
  D --> E[Model history replay]
  D --> F[Chat display filter]
Loading

Technical review

Best possible solution:

Land the approved suppression removal through the existing recorder, preserving hidden display and explicit caller suppression.

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

Current-main source still suppresses the completion user turn, matching the supplied before-fix Gateway trace; no target code was executed during this read-only review.

Is this the best way to solve the issue?

This is the smallest complete fix: remove the special suppression, reuse existing hidden-input persistence, and retain one regression that reads the stored transcript.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4846765d3e20.

Provenance checked

  • Ordinary subagent completion prompt suppression changes intended behavior with a stated reason (fix: hide subagent announce handoff prompts #79618: Prevent internal announce wrappers from appearing in raw requester transcripts and visible chat history.)
  • Durable Gateway user-turn admission keeps the original intent (358c06e: Persist accepted agent turns before acknowledgement so detached execution cannot leave accepted input without a durable record.)
  • Private parent completion persistence keeps the original intent (7a168d3: Retain private completion input through the existing recorder while suppressing automatic external delivery.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 358c06e adds src/gateway/agent-turn/agent-run-user-turn.ts:132 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 358c06ec9599; files: src/gateway/agent-turn/agent-run-user-turn.ts)

PR surface

Source -25, Tests -6. Total -31 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 2 27 -25
Tests 2 42 48 -6
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 44 75 -31

Review metrics

Metric Value Why it matters
Production versus test changes Production +2/−27; tests +42/−48 Removes obsolete suppression machinery and replaces mocked policy assertions with one distinct persistence regression in an existing suite.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #181672
Summary: This PR addresses missing completion-user-turn persistence; owner-list and pinned-system-prompt cache changes address separate mechanisms.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on maintainer: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Repeated completion turns lose reusable history prefixes, increasing model cost and latency without blocking the conversation.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-23T14:13:02.021Z sha 1bab55a :: blocked before merge. :: none
  • reviewed 2026-10-23T14:59:46.418Z sha e1201d7 :: blocked before merge. :: none

Reviewed October 26, 2026, 12:17 AM ET / 04:17 UTC (Revision 3).

…nscript

Replace the mocked agentCommand call-shape assertion with a regression at the user-turn owner: a subagent completion handoff prepared through prepareAgentRunUserTurn is appended to the session transcript as a hidden inter_session user row.
@masatohoshino

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@steipete

Copy link
Copy Markdown
Contributor

Maintainer decision (Peter, 2026-10-25): approved. Ordinary subagent-completion prompts may be retained as hidden (display: false) raw-transcript rows through the existing provenance/recorder owner, which reverses the earlier #79618 exclusion for this case. Visible chat history stays unchanged and no schema change is involved; the benefit is that completion turns stop breaking the prompt-cache prefix. Thanks @masatohoshino. Landing through the normal review/CI gates.

@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. labels Oct 26, 2026
@steipete
steipete merged commit e62f224 into openclaw:main Oct 26, 2026
159 of 163 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…cache (openclaw#181673)

* fix(gateway): keep subagent completion prompts in model history

The Gateway agent turn skipped persisting the user turn of a subagent completion handoff, while the turn's hidden runtime context was still saved after it. The next request then replayed a different history and lost the prompt cache. Persist the turn through the existing path with its inter_session provenance and display: false, as the steering path already does, and remove the unused helper.

* test(gateway): prove subagent completion prompts reach the stored transcript

Replace the mocked agentCommand call-shape assertion with a regression at the user-turn owner: a subagent completion handoff prepared through prepareAgentRunUserTurn is appended to the session transcript as a hidden inter_session user row.
orswn added a commit to getboon/openclaw that referenced this pull request Oct 30, 2026
…ielding (#314)

A parent agent that spawns sub-agents and calls sessions_yield is idle
while the children run. When a child finishes, the gateway agent method
runs a parent turn with the child result. That turn did not save its
prompt to the parent transcript. The model saw the result once, in that
turn only. On the next wake the result was gone, so the parent waited
for children that had already finished and never sent its final answer.

The suppression came from upstream "fix: hide subagent announce
handoff prompts" (openclaw#79618). Its goal was to hide the handoff prompt in
chat history. The chat display projection already hides user rows with
subagent_announce provenance, so dropping the transcript row is not
needed for that goal. Upstream removed the same suppression in
openclaw#181673.

Remove the automatic suppression for sub-agent completion handoffs. The
completion turn now saves a user row with inter_session /
subagent_announce provenance that carries the child result. Callers that
pass suppressPromptPersistence explicitly keep their behavior.

Trade-off: when a completion delivery stays pending, for example in a
session with no deliverable channel, the agent steering queue replays it
on each wake, and a sessions_yield abort returns the leased items to the
queue. That replay is now saved in each wake row too. A TODO marks the
release on the yield abort; fixing it changes the steering lease rules.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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]: The owner turn after a subagent completion misses the prompt cache because the completion's user message is never saved

2 participants