Repository navigation
fix(agents): agent cannot fix or retry generated media after it completes - #174696
Conversation
…ary completion turn
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThe host delivers generated media before an ordinary agent turn that can inspect, correct, or retry the result. Example: An image-generation request returns HTTP 500.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR fixes a current generated-media completion limitation, and no actionable patch defects remain; the documented CI failure is inherited and has a maintainer override. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherBackground generation enters the durable session queue, which hands media to outbound delivery or the owning transcript before dispatching the requester’s completion turn. flowchart LR
A[Background generation] --> B[Durable session queue]
B --> C[Host media delivery]
C --> D[Outbound queue or transcript]
D --> E[Ordinary completion turn]
E --> F[Inspect or retry generation]
Technical reviewBest possible solution: Keep media delivery under the existing durable host owners while giving the agent its ordinary tools for quality checks and retries. Do we have a high-confidence way to reproduce the issue? Current-main source establishes the restricted completion toolset, and the supplied Telegram comparison demonstrates its user-visible failure; this review executed no target code. Is this the best way to solve the issue? Separating deterministic delivery from model judgment fixes the owning boundary and removes competing retry policy while retaining outbound custody and session authorization. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 27f8c47bbb6f. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource -461, Tests -732, Other -2. Total -1195 across 37 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (4 earlier review cycles)
Reviewed October 16, 2026, 11:06 PM ET / October 17, 2026, 03:06 UTC (Revision 5). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Maintainer override: the only red required checks on head 71fe917 are unrelated to this PR.
Every other CI job on this head is green. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Landed in 749464c. Bug: a finished image/video/music generation was delivered by a restricted "recovery" agent turn. That turn had no Fix: the host sends the media through the durable queue. The send is bound to the original requester, fenced, and settled from the outbound receipt, so it is never sent twice. One ordinary completion turn with the normal toolset then follows. The agent is told the files were already sent and is asked to check the result and continue if it falls short. Proof: focused queue/sentinel/announce suites, and Telegram Test Server runs on the exact head:
Thanks to @Oldrich333 for the #169118 report. This change also removes the CLI message-tool mismatch it describes. |
…etes (openclaw#174696) Related: openclaw#169118 ## What Problem This Solves Fixes: after `image_generate` (or video/music generation) finishes, the agent cannot check or fix the result. A failed generation is only reported and never retried. A wrong image is captioned "not fully fixed yet" and left as is. The cause: every generated-media completion, failed ones included, ran as a durable "recovery" agent turn. That turn forced `forceRestartSafeTools`, `disableMessageTool` and an exact host media allowlist. The model saw only restart-safe tools: `image_generate` and `message` were gone. If evidence was missing, a re-arm loop replayed the whole turn. The tool list also changed between normal turns and completion turns, which broke the prompt cache. ## User Impact - Generated media reaches the chat exactly once, sent by the host. - The agent then gets one ordinary completion turn with its normal toolset. It can compare the result with the request and generate again, or retry a failed generation. - The completion turn's tool schema matches an ordinary completion turn, not a restart-safe subset (37 of 38 tools in the live run below, against 11 before). ## Why This Change Was Made The host owns the bytes and the agent owns the conversation. No model turn sits in the media delivery path. 1. **Host delivery.** The durable session-delivery row (same `agentTurn` entry kind and fields, no schema change) now sends its `expectedMediaUrls` with a deterministic outbound send. The send uses a stable delivery intent per row, so the outbound queue's receipt dedupes replays. It also carries the original requester session (session id and lifecycle revision), so outbound custody refuses the send, including a later recovery replay, if that session was reset or replaced. For internal routes, the media goes into the owning transcript as one idempotent host message. The send is fenced: a replay of a started send settles only from its outbound receipt and never sends again, even after the receipt has expired. An ambiguous send (a possible send, or a terminally failed or missing outbound receipt) dead-letters instead of sending again. 2. **One ordinary completion turn.** After the send settles, the row advances (media list cleared, a host notice that the files were already sent is put before the event). The next drain then runs one `agent` turn with the requester's normal tools and reply policy: no `forceRestartSafeTools`, no `disableMessageTool`, no media allowlist. The turn keeps its start fence, so an interrupted turn is never replayed. If only the follow-up turn is lost after the media was delivered, the row settles as delivered. Otherwise the media task would report the media as undelivered and retain it a second time (visible on webchat). 3. **Failures.** A failed generation has no media, so its row skips the send and runs only the ordinary completion turn. It keeps the durable row, not the direct announce path, because the direct path rejects generated-media events in cron-run sessions. 4. **New instruction.** The completion instruction tells the model that the host already sent the files. It asks the model to check the result against the request and continue (for example, generate again with adjusted parameters) when the result falls short or the failure looks recoverable. Otherwise the model gives a short reply. The model judges quality; no code judge was added. 5. **Removed:** the media evaluator and re-arm loop, `internalDeliveryMediaUrls` / `internalDeliverySuppressText` plumbing, the media branch of the recovery-options invariant (`resolveCommandRecoveryOptions`), `constrainRestartRecoveryDeliveryPayloads`, `buildGeneratedMediaDeliveryContext`, the retry prompt, and evidence helpers only that path used. `forceRestartSafeTools` stays for real restart recovery (openclaw#104997). Upgrade: pending media rows from older versions drain through the new path. The host transcript step uses its own stable key, so it cannot collide with a transcript entry an older release already wrote. A row that a previous version re-armed is host-sent and then gets the completion turn (covered by a test). A row with a started attempt dead-letters, as before. This replaces the queued agent turn that openclaw#108024 introduced for exactly-once delivery (openclaw#87989, openclaw#87995). It also removes the CLI message-tool mismatch in openclaw#169118, because the completion turn no longer restricts the message tool. ## Evidence **Live Telegram (Test Server, real user account, mock model provider that logs the tools offered on each request). "This PR" rows ran on the exact head build:** | Run | Build | What happened in the chat | Completion turn tools | | --- | --- | --- | --- | | A: generate | main | "Working on it." → 1 photo, captioned "The date ring is wrong but I cannot regenerate from this turn." | 11 restart-safe tools, no `image_generate`, no `message` | | A: generate | this PR | "Working on it." → photo 1 → "Working on it." → photo 2 → final reply | 37 tools incl. `image_generate` and `message`. It called `image_generate` again. | | C: provider fails | main | "Working on it." → "Image generation failed and I cannot retry here." | 11 tools | | C: provider fails | this PR | "Working on it." → retry → 1 photo → final reply | 37 tools. It retried. | | D: restart mid-send | this PR | Telegram accepted `sendPhoto`, the response was held, the Gateway restarted, then the response was released. Exactly 1 photo. | Outbound recovery refused a blind replay. The row dead-lettered. No duplicate. | On every run, each photo appeared as exactly one native Telegram message. The user turn offered 38 tools. The one tool missing from the completion turn is `transcripts`, which needs a human sender or operator identity. Ordinary subagent completion turns also lack it. **Live Telegram with a real model** (`gpt-6-sol`, real `gpt-image-1`, Code Mode on as in production, Tool Search off). A logging proxy in front of the OpenAI API recorded the tools offered on each request and injected one fault per run: | Run | Injected fault | What happened | | --- | --- | --- | | Wrong result | First image returned as a blank grey square | The completion turn opened it with `view_image`, saw it was blank, built a corrected calendar with `exec`, checked it, and sent it ("The first image didn't render…"). 2 photos, each once. | | Failed generation | First image request returned HTTP 500 | The completion turn said "hit a temporary image-service error, retried", called `image_generate` again, real `gpt-image-1` returned 200. 1 photo, then the reply. | In Code Mode, the user turn and the completion turn offered the identical tool list (`exec`, `message`, `sessions_yield`, `view_image`, `wait`), so the prompt cache holds across them. With Code Mode off, a separate run showed 38 vs 37 tools (`transcripts`, see above). **Focused tests:** the three `server-restart-sentinel*` suites pass. They cover the host send before the completion turn, no resend after a crash between send and turn, dead-letter on a possible send or a terminal outbound failure, deferral while outbound recovery owns the send, safe retry when the send provably did not reach the chat, failed generation, cron continuation, the internal-route transcript, an old re-armed row, requester binding through the real queue, and a refused follow-up turn after delivered media. Queue, recovery, announce, media-background and managed-attachment suites also pass (258 tests). CI is green on the head apart from one ratchet failure that comes from `main` and also fails on unrelated PRs (see the maintainer override comment). Requester revocation: the binding test asserts the original requester (session id, lifecycle revision) reaches outbound custody. The existing outbound integration test `deliver.session-generation.integration.test.ts` ("replays every same-generation result and terminalizes only revoked unsent results") proves that custody refuses a revoked generation before platform I/O, including on recovery. Not covered: in run D the completion turn does not run, because the row dead-letters on the ambiguous send. That is the intended exactly-once trade-off. ## Merge danger Two-way door. A revert restores the old queued agent turn. The rows this PR writes use the existing entry kind and fields, so the old code reads them. Blast radius: every generated-media completion on every channel, including internal webchat delivery and cron-run sessions. Co-authored-by: Ayaan Zaidi <[email protected]>
…fecycle suites - session-recipient-authority.incognito-actor: upstream made incognito sessions memory-only actor owned (openclaw#170712) and deleted the old actor modules. The suite now creates and writes incognito sessions through the memory owner (acquireSessionActorStorage + commitMemory, bound with runWithSessionActorStorage) and keeps every invariant: capture through the collaboration path is refused with the dedicated-owner message; capture while the binding is active is refused (and never creates the native store); a native epoch for the key is not current; a narrowing visibility patch through the memory writer does not run afterPersistInTransaction and leaves authority non-current. Ownership is now decided by the incognito key, so the old "native capture before any actor exists" step has no equivalent: the suite seeds the epoch row directly and checks a durable control key is current while the incognito key is not. - session-history-budget-owner: `typescript/unstable/ast` became `typescript/ast` with the TypeScript update, as upstream imports it. - session-utils.queued-collector-rollback-custody: openclaw#177787 removed killSubagentRunAdmin / control.preparePublication and openclaw#175837 context.chatAbortControllers; the Stop is now held right after its committed kill write (spy on markSubagentRunTerminated), still inside the retirement publication the collector waits on. Assertions unchanged; the failure case fails the Stop after that write. - session-delivery-queue.storage-lifecycle: upstream openclaw#174696 removed suppressTextDelivery from SessionDeliveryAgentRunUpdate and deleted the same two lines from its own copy of this case; this fork split does the same. Proof on this tree (run-vitest, 3 shards): storage-lifecycle 7/7, incognito-actor 2/2, history-budget-owner 13/13, rollback-custody 2/2. Refs #1475 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #169118
What Problem This Solves
Fixes: after
image_generate(or video/music generation) finishes, the agent cannot check or fix the result. A failed generation is only reported and never retried. A wrong image is captioned "not fully fixed yet" and left as is.The cause: every generated-media completion, failed ones included, ran as a durable "recovery" agent turn. That turn forced
forceRestartSafeTools,disableMessageTooland an exact host media allowlist. The model saw only restart-safe tools:image_generateandmessagewere gone. If evidence was missing, a re-arm loop replayed the whole turn. The tool list also changed between normal turns and completion turns, which broke the prompt cache.User Impact
Why This Change Was Made
The host owns the bytes and the agent owns the conversation. No model turn sits in the media delivery path.
agentTurnentry kind and fields, no schema change) now sends itsexpectedMediaUrlswith a deterministic outbound send. The send uses a stable delivery intent per row, so the outbound queue's receipt dedupes replays. It also carries the original requester session (session id and lifecycle revision), so outbound custody refuses the send, including a later recovery replay, if that session was reset or replaced. For internal routes, the media goes into the owning transcript as one idempotent host message. The send is fenced: a replay of a started send settles only from its outbound receipt and never sends again, even after the receipt has expired. An ambiguous send (a possible send, or a terminally failed or missing outbound receipt) dead-letters instead of sending again.agentturn with the requester's normal tools and reply policy: noforceRestartSafeTools, nodisableMessageTool, no media allowlist. The turn keeps its start fence, so an interrupted turn is never replayed. If only the follow-up turn is lost after the media was delivered, the row settles as delivered. Otherwise the media task would report the media as undelivered and retain it a second time (visible on webchat).internalDeliveryMediaUrls/internalDeliverySuppressTextplumbing, the media branch of the recovery-options invariant (resolveCommandRecoveryOptions),constrainRestartRecoveryDeliveryPayloads,buildGeneratedMediaDeliveryContext, the retry prompt, and evidence helpers only that path used.forceRestartSafeToolsstays for real restart recovery (fix: resume replay-safe work after gateway restarts #104997).Upgrade: pending media rows from older versions drain through the new path. The host transcript step uses its own stable key, so it cannot collide with a transcript entry an older release already wrote. A row that a previous version re-armed is host-sent and then gets the completion turn (covered by a test). A row with a started attempt dead-letters, as before.
This replaces the queued agent turn that #108024 introduced for exactly-once delivery (#87989, #87995). It also removes the CLI message-tool mismatch in #169118, because the completion turn no longer restricts the message tool.
Evidence
Live Telegram (Test Server, real user account, mock model provider that logs the tools offered on each request). "This PR" rows ran on the exact head build:
image_generate, nomessageimage_generateandmessage. It calledimage_generateagain.sendPhoto, the response was held, the Gateway restarted, then the response was released. Exactly 1 photo.On every run, each photo appeared as exactly one native Telegram message. The user turn offered 38 tools. The one tool missing from the completion turn is
transcripts, which needs a human sender or operator identity. Ordinary subagent completion turns also lack it.Live Telegram with a real model (
gpt-6-sol, realgpt-image-1, Code Mode on as in production, Tool Search off). A logging proxy in front of the OpenAI API recorded the tools offered on each request and injected one fault per run:view_image, saw it was blank, built a corrected calendar withexec, checked it, and sent it ("The first image didn't render…"). 2 photos, each once.image_generateagain, realgpt-image-1returned 200. 1 photo, then the reply.Correction after landing (measured with OpenAI
cached_tokens): the completion turn still misses the prompt cache in both modes. With Code Mode off, its tool list lackstranscripts(37 vs 38). In Code Mode the tool list is identical, but the system prompt's catalog line says 3 omitted tools instead of 4, for the same reason. Either difference gave 0 cached tokens on the completion turn's first request (about 20k–26k input tokens), against a 97–99% hit for normal follow-ups. Tracked as a follow-up.Focused tests: the three
server-restart-sentinel*suites pass 73/73. They cover the host send before the completion turn, no resend after a crash between send and turn, dead-letter on a possible send or a terminal outbound failure, deferral while outbound recovery owns the send, safe retry when the send provably did not reach the chat, failed generation, cron continuation, the internal-route transcript, an old re-armed row, requester binding through the real queue, and a refused follow-up turn after delivered media. Queue, recovery, announce, media-background and managed-attachment suites also pass (258 tests). CI is green on the head.Requester revocation: the binding test asserts the original requester (session id, lifecycle revision) reaches outbound custody. The existing outbound integration test
deliver.session-generation.integration.test.ts("replays every same-generation result and terminalizes only revoked unsent results") proves that custody refuses a revoked generation before platform I/O, including on recovery.Not covered: in run D the completion turn does not run, because the row dead-letters on the ambiguous send. That is the intended exactly-once trade-off.
Merge danger
Two-way door. A revert restores the old queued agent turn. The rows this PR writes use the existing entry kind and fields, so the old code reads them. Blast radius: every generated-media completion on every channel, including internal webchat delivery and cron-run sessions.