Skip to content

fix(agents): wake owning session after generated-media direct delivery - #108024

Merged
steipete merged 17 commits into
mainfrom
feat/generated-media-direct-delivery-wake
Jul 15, 2026
Merged

steipete merged 17 commits into
mainfrom
feat/generated-media-direct-delivery-wake

Conversation

@clawsweeper

@clawsweeper clawsweeper Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where a background image, music, or video generation completion could be delivered directly after its original agent turn was interrupted, leaving the owning session without a durable continuation. The attachment could arrive, but the agent might never get a reliable turn to explain it, continue the conversation, or reconcile delivery after restart.

Why This Change Was Made

Generated-media completion now enters a durable SQLite-backed session delivery queue and resumes the owning session through the normal gateway agent loop. The queue fixes the route and exact media set, disables the model-facing message tool for this host-owned turn, and settles only from durable terminal delivery evidence.

This replaces the wake-only side path. Pre-admission failures retry safely; accepted or in-flight work keeps a durable ownership fence; terminal ambiguity fails closed through bounded reconciliation and dead-lettering. Internal completions append media to the owning transcript instead of invoking an external transport.

User Impact

Background generated media now receives a reliable agent continuation even when the original turn is steered, aborted, or interrupted by restart. Users get normal agent-loop behavior without duplicate attachments or orphaned session state.

Release-note context: improve generated-media completion recovery so interrupted background generations resume through the owning agent session without duplicate delivery.

Evidence

  • Focused local suite: 930 passed, 1 existing skip across 9 Vitest shards.
  • Final focused regressions: 87 passed across restart sentinel, generated-media emergency wake, delivery evidence, and queue runtime suites.
  • Blacksmith Testbox changed gate on prior head 1c41aca077235227ced699847188d0299bec34fd: core and core-test typecheck, full core/scripts lint, format, SDK/boundary/storage guards all passed in 21m36s (run).
  • Follow-up hosted-gate fixes on 1c499f7526c64f893d5d9d1dfa84f7b287e68a11: zero Madge cycles, zero dead exports, targeted lint/format green.
  • git diff --check and max-lines ratchet passed.
  • Final structured autoreview: no accepted/actionable findings.

No root changelog edit: release-note context is captured above for release generation.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Jul 15, 2026
@steipete steipete self-assigned this Jul 15, 2026
steipete and others added 14 commits July 15, 2026 11:45
When a background media generation (image/music/video) completes but the
requester's agent turn cannot be woken, delivery falls back to sending the
media straight to the channel. The owning session never learned about it,
leaving the attachment orphaned with no agent follow-up.

Queue a system event plus a scoped heartbeat wake after both direct
fallback paths (announce delivery and the shared background lifecycle) so
the agent continues the conversation in its own voice. Subagent requester
sessions skip the heartbeat since their completions route via announce.

Co-Authored-By: Claude Fable 5 <[email protected]>
@steipete
steipete force-pushed the feat/generated-media-direct-delivery-wake branch from 48fe4b8 to 1c41aca Compare July 15, 2026 19:18
@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime size: XL triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup. and removed size: M labels Jul 15, 2026
@steipete
steipete merged commit 15a304d into main Jul 15, 2026
114 checks passed
@steipete
steipete deleted the feat/generated-media-direct-delivery-wake branch July 15, 2026 19:54
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 16, 2026
openclaw#108024)

* fix(agents): wake owning session after generated-media direct delivery

When a background media generation (image/music/video) completes but the
requester's agent turn cannot be woken, delivery falls back to sending the
media straight to the channel. The owning session never learned about it,
leaving the attachment orphaned with no agent follow-up.

Queue a system event plus a scoped heartbeat wake after both direct
fallback paths (announce delivery and the shared background lifecycle) so
the agent continues the conversation in its own voice. Subagent requester
sessions skip the heartbeat since their completions route via announce.

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

* fix(agents): persist generated media session handoffs

Co-authored-by: Molty <[email protected]>

* chore: prune max-lines baseline

* fix(agents): harden durable media handoffs

* fix(agents): charge media retries once

* chore: refresh max-lines baseline

* fix(agents): persist delivery settlement cleanup

* fix(agents): fence interrupted media delivery

* fix(agents): fence durable handoff admission

* fix(agents): reconcile terminal handoffs at retry limit

* fix(agents): align durable handoff types

* test(agents): type durable handoff fixtures

* fix: satisfy session delivery lint

* fix: avoid payload map spreads

* fix: satisfy durable handoff gates

* test: align generated media handoff expectations

* fix: avoid serializing session recovery state during load

---------

Co-authored-by: Molty <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
openclaw#108024)

* fix(agents): wake owning session after generated-media direct delivery

When a background media generation (image/music/video) completes but the
requester's agent turn cannot be woken, delivery falls back to sending the
media straight to the channel. The owning session never learned about it,
leaving the attachment orphaned with no agent follow-up.

Queue a system event plus a scoped heartbeat wake after both direct
fallback paths (announce delivery and the shared background lifecycle) so
the agent continues the conversation in its own voice. Subagent requester
sessions skip the heartbeat since their completions route via announce.

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

* fix(agents): persist generated media session handoffs

Co-authored-by: Molty <[email protected]>

* chore: prune max-lines baseline

* fix(agents): harden durable media handoffs

* fix(agents): charge media retries once

* chore: refresh max-lines baseline

* fix(agents): persist delivery settlement cleanup

* fix(agents): fence interrupted media delivery

* fix(agents): fence durable handoff admission

* fix(agents): reconcile terminal handoffs at retry limit

* fix(agents): align durable handoff types

* test(agents): type durable handoff fixtures

* fix: satisfy session delivery lint

* fix: avoid payload map spreads

* fix: satisfy durable handoff gates

* test: align generated media handoff expectations

* fix: avoid serializing session recovery state during load

---------

Co-authored-by: Molty <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
obviyus added a commit that referenced this pull request Oct 17, 2026
…etes (#174696)

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`, `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 (#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:**

| 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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui gateway Gateway runtime size: XL triage: dirty-candidate Candidate: broad unrelated surfaces; may need splitting or cleanup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant