Skip to content

fix(gateway,ui): restore managed media transcript persistence in webchat - #68821

Closed
Ittiz wants to merge 6 commits into
openclaw:mainfrom
Ittiz:forge/pr2-managed-image-bridge-upstream-polish
Closed

Ittiz wants to merge 6 commits into
openclaw:mainfrom
Ittiz:forge/pr2-managed-image-bridge-upstream-polish

Conversation

@Ittiz

@Ittiz Ittiz commented Apr 19, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Problem: assistant replies with managed media, especially image-only replies and agent-run audio replies, could render live in webchat/control UI but fail to persist correctly into transcript/history.
  • Why it matters: users could see a reply in the moment, then lose it from chat.history or get inconsistent follow-up rendering/auth behavior on reload.
  • What changed: tightened the managed-image bridge across gateway + UI, limited bridging to full-image previews, fixed transcript injection/persistence for agent-run webchat audio replies, and hardened the relevant test coverage.
  • What did NOT change (scope boundary): this does not add a new media transport model or redesign the overall chat transcript architecture.

Change Type (select all)

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

Scope (select all touched areas)

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

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: the agent-started webchat completion path could skip the transcript append fallback used by the non-agent path, so media replies could be delivered live without being durably recorded. Managed-image handling also had UI/gateway edge cases around preview reconciliation and authenticated media access.
  • Missing detection / guardrail: coverage did not reliably lock in image-only assistant reply persistence plus the agent-run audio transcript path.
  • Contributing context (if known): a few managed-image tests were also flaky because they depended on a broader dispatch path instead of driving the seam directly.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file:
    • src/gateway/server.chat.gateway-server-chat.test.ts
    • src/gateway/managed-image-attachments.test.ts
    • ui/src/ui/views/chat.test.ts
    • ui/src/ui/chat/gateway-http-auth.test.ts
  • Scenario the test should lock in: image-only and audio-capable assistant replies that render live must also persist as transcript/history entries and remain reload-safe in UI.
  • Why this is the smallest reliable guardrail: the bug sits at the gateway/UI seam, not in isolated helpers.
  • Existing test that already covers this (if any): some managed-image coverage existed, but it did not reliably cover the failing path.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

  • Image-only assistant replies are more reliably preserved in chat history.
  • Agent-run webchat audio replies are now durably recorded in transcripts instead of being live-only.
  • Managed image previews/auth behavior is more consistent after reload/reopen.

Diagram (if applicable)

Before: [assistant media reply] -> [live webchat render] -> [missing/incomplete transcript entry] -> [history/reload inconsistency]
After: [assistant media reply] -> [gateway transcript append] -> [managed media recorded in transcript] -> [stable history + reload rendering]

Security Impact (required)

  • 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
  • If any Yes, explain risk + mitigation: N/A

Repro + Verification

Environment

  • OS: Linux
  • Runtime/container: local OpenClaw workspace/dev environment
  • Model/provider: webchat path, agent-run + gateway transcript path
  • Integration/channel (if any): webchat / Control UI
  • Relevant config (redacted): standard local OpenClaw config

Steps

  1. Trigger an assistant reply that contains managed media, especially an image-only or audio reply.
  2. Observe that the reply renders live in webchat.
  3. Reload or inspect transcript/history.
  4. Confirm the assistant media reply is still present and correctly represented.

Expected

Assistant media replies render live and persist into transcript/history.

Actual

Some replies rendered live but were not durably persisted, causing missing or inconsistent history on reload.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios:
    • targeted gateway chat tests for managed-image persistence paths
    • targeted UI chat tests
    • targeted managed-image attachment tests
    • live webchat audio smoke test after rebuild/restart
  • Edge cases checked:
    • image-only assistant replies
    • agent-run audio reply persistence path
    • follow-up preview behavior
  • What you did not verify:
    • broad end-to-end cross-channel coverage outside the targeted webchat/control UI path

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No
  • If yes, exact upgrade steps: N/A

Risks and Mitigations

  • Risk: managed-media rendering and transcript persistence touch both gateway and UI seams.
  • Mitigation: targeted gateway/UI regression coverage was added and hardened.
  • Risk: media auth/reload behavior can regress in subtle ways.
  • Mitigation: explicit UI auth-path coverage and live smoke verification.

Ittiz added 6 commits April 14, 2026 13:52
(cherry picked from commit 5360330805bd26bb0415f094650e9b329f5e0a6d)
- await async webchat audio block construction before transcript append
- allow transcript-local audio files as embedding roots for agent replies
- await the audio transcript append from the reply dispatcher
- keeps the managed-image test slice green
@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime size: XL labels Apr 19, 2026
@greptile-apps

greptile-apps Bot commented Apr 19, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes two related persistence bugs: (1) agent-run webchat completions could skip the transcript-append fallback used by the non-agent path, so media replies were delivered live but not durably recorded; (2) managed-image records lacked a messageId link on the non-agent path, causing the auth/cleanup gate (recordMatchesTranscriptMessage) to 404 on reload. The fix adds appendWebchatAgentAudioTranscriptIfNeeded for the agent-run audio path, tightens parseManagedOutgoingRoute to the /full variant only, and adds UI-side auth header and preview-reconciliation hardening. Test coverage targets the gateway/UI seam directly.

Confidence Score: 5/5

Safe to merge; remaining findings are style/minor-robustness P2 items that do not block correctness.

All P0/P1 paths are covered: transcript append idempotency is enforced, auth gate remains strict, and the new audio path has test coverage. The two inline comments are P2 style observations (forward variable reference, incomplete regex) that do not affect runtime behavior for current call sites.

src/gateway/server-methods/chat.ts — the agentRunStarted ordering and single-audio-per-run gate are worth a second read to confirm intended semantics.

Comments Outside Diff (1)

  1. src/gateway/server-methods/chat.ts, line 2171-2213 (link)

    P2 appendedWebchatAgentAudio gate limits to first successful payload only

    appendedWebchatAgentAudio is set to true after the first successful audio transcript append (line 2206), which means any subsequent media-bearing block/final payloads from the same agent run are silently skipped. If an agent emits multiple audio replies in one run, only the first is ever persisted. Additionally, agentRunStarted is read at line 2172 but declared with let at line 2250 — while valid JavaScript closure semantics mean this works at runtime, the forward reference makes the control flow harder to follow at a glance.

    Consider declaring agentRunStarted before the function that reads it, and documenting the single-audio-per-run intent with a comment if it is intentional.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/gateway/server-methods/chat.ts
    Line: 2171-2213
    
    Comment:
    **`appendedWebchatAgentAudio` gate limits to first successful payload only**
    
    `appendedWebchatAgentAudio` is set to `true` after the first successful audio transcript append (line 2206), which means any subsequent media-bearing block/final payloads from the same agent run are silently skipped. If an agent emits multiple audio replies in one run, only the first is ever persisted. Additionally, `agentRunStarted` is read at line 2172 but declared with `let` at line 2250 — while valid JavaScript closure semantics mean this works at runtime, the forward reference makes the control flow harder to follow at a glance.
    
    Consider declaring `agentRunStarted` before the function that reads it, and documenting the single-audio-per-run intent with a comment if it is intentional.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/gateway/server-methods/chat.ts
Line: 2171-2213

Comment:
**`appendedWebchatAgentAudio` gate limits to first successful payload only**

`appendedWebchatAgentAudio` is set to `true` after the first successful audio transcript append (line 2206), which means any subsequent media-bearing block/final payloads from the same agent run are silently skipped. If an agent emits multiple audio replies in one run, only the first is ever persisted. Additionally, `agentRunStarted` is read at line 2172 but declared with `let` at line 2250 — while valid JavaScript closure semantics mean this works at runtime, the forward reference makes the control flow harder to follow at a glance.

Consider declaring `agentRunStarted` before the function that reads it, and documenting the single-audio-per-run intent with a comment if it is intentional.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: ui/src/ui/chat/grouped-render.ts
Line: 97-99

Comment:
**`isImageOnlyUrlToken` regex misses `/full` variant**

The pattern `/\/api\/chat\/media\/outgoing\/.+\/(download|open)$/` matches the `/download` and `/open` route variants but not `/full`, which is the only variant actually generated by `buildOutgoingVariantUrl`. In practice this is benign because managed image URLs appear in the `imageUrls` Set (populated from `extractImages` content blocks) and are matched by `imageUrls.has(normalized)` before the regex path is reached. But if a URL ever appears in markdown text outside a content block, the regex wouldn't suppress it.

```suggestion
    if (/\/api\/chat\/media\/outgoing\/.+\/(download|open|full)$/.test(pathname)) {
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(gateway): persist agent-run webchat ..." | Re-trigger Greptile

Comment on lines +97 to +99
if (/\/api\/chat\/media\/outgoing\/.+\/(download|open)$/.test(pathname)) {
return true;
}

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.

P2 isImageOnlyUrlToken regex misses /full variant

The pattern /\/api\/chat\/media\/outgoing\/.+\/(download|open)$/ matches the /download and /open route variants but not /full, which is the only variant actually generated by buildOutgoingVariantUrl. In practice this is benign because managed image URLs appear in the imageUrls Set (populated from extractImages content blocks) and are matched by imageUrls.has(normalized) before the regex path is reached. But if a URL ever appears in markdown text outside a content block, the regex wouldn't suppress it.

Suggested change
if (/\/api\/chat\/media\/outgoing\/.+\/(download|open)$/.test(pathname)) {
return true;
}
if (/\/api\/chat\/media\/outgoing\/.+\/(download|open|full)$/.test(pathname)) {
Prompt To Fix With AI
This is a comment left during a code review.
Path: ui/src/ui/chat/grouped-render.ts
Line: 97-99

Comment:
**`isImageOnlyUrlToken` regex misses `/full` variant**

The pattern `/\/api\/chat\/media\/outgoing\/.+\/(download|open)$/` matches the `/download` and `/open` route variants but not `/full`, which is the only variant actually generated by `buildOutgoingVariantUrl`. In practice this is benign because managed image URLs appear in the `imageUrls` Set (populated from `extractImages` content blocks) and are matched by `imageUrls.has(normalized)` before the regex path is reached. But if a URL ever appears in markdown text outside a content block, the regex wouldn't suppress it.

```suggestion
    if (/\/api\/chat\/media\/outgoing\/.+\/(download|open|full)$/.test(pathname)) {
```

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 76e5fe0e8b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +476 to +478
if (sessionKeyFilter && record.sessionKey !== sessionKeyFilter) {
retainedCount += 1;
continue;

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.

P1 Badge Preserve non-target files in session-scoped cleanup

When sessionKey is provided, records from other sessions are skipped here, but their original.path/thumbnail.path are never added to referencedPaths. The later orphan-file sweep still runs globally and can delete those skipped sessions’ media files, so a chat.history call for one session can silently break managed images in other active sessions while leaving their JSON records behind.

Useful? React with 👍 / 👎.

Comment on lines +1438 to +1440
if (normalized.length === 0) {
return rawTextPayloadCount > 0 ? [{ type: "text", text: "" }] : undefined;
}

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.

P2 Badge Avoid emitting empty assistant blocks for suppressed replies

This branch fabricates [{ type: "text", text: "" }] whenever raw text existed but normalization removed every payload (for example NO_REPLY or directive-only replies). That causes chat.send to append blank assistant entries to transcript/history instead of suppressing the turn, creating invisible-but-persistent messages that can affect ordering and downstream history consumers.

Useful? React with 👍 / 👎.

Comment on lines +852 to +854
const blobUrl = URL.createObjectURL(blob);
managedImageBlobUrlResolvedCache.set(cacheKey, blobUrl);
return blobUrl;

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.

P2 Badge Revoke cached managed-image blob URLs after rendering

Each successful managed-image fetch creates a blob URL and stores it in managedImageBlobUrlResolvedCache, but this commit does not add any call site for cleanupUnusedManagedImagePreviewBlobUrls (repo-wide search only finds its export). As users view more unique images, blob URLs and backing blobs accumulate for the page lifetime, causing unbounded memory growth in long-lived Control UI sessions.

Useful? React with 👍 / 👎.

@Ittiz
Ittiz marked this pull request as draft April 19, 2026 05:05
@Ittiz Ittiz closed this Apr 19, 2026
@Ittiz
Ittiz deleted the forge/pr2-managed-image-bridge-upstream-polish branch April 19, 2026 05:16
@prtags

prtags Bot commented Apr 23, 2026

Copy link
Copy Markdown

Related work from PRtags group intent-mastiff-ytno

Title: Open PR duplicate: managed media transcript persistence

Number Title
#68821* fix(gateway,ui): restore managed media transcript persistence in webchat
#69500 fix(gateway,ui): restore managed media transcript persistence in webchat
#70383 fix(gateway,ui): restore managed media transcript persistence in webchat

* This PR

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

Labels

app: web-ui App: web-ui gateway Gateway runtime size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Webchat/Control UI does not render images generated by image_generate tool

1 participant