Skip to content

fix(gateway): images sent to Claude CLI sessions show as raw cache-path links in chat history - #130463

Merged
jalehman merged 9 commits into
mainfrom
fix/cli-image-history-mention-strip
Aug 28, 2026
Merged

jalehman merged 9 commits into
mainfrom
fix/cli-image-history-mention-strip

Conversation

@jalehman

@jalehman jalehman commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users sending images to a Claude CLI-backed session would see the image appear in WebChat/Control UI chat history as a raw path link (for example @/…/.openclaw-cli-images/<sha>.png) instead of the inline thumbnail preview that API-backed models show, plus a duplicate user row for the same turn.

Why This Change Was Made

The CLI runner cannot pass structured image blocks to the Claude CLI, so it appends @<image cache path> mention lines to the prompt it hands the CLI. Claude Code records that mutated prompt as its user message, and the transcript importer merges it back into chat history, where it does not text-dedupe against OpenClaw's local media-bearing user row.

For new image turns, the runner now adds an opaque correlation key derived from the persisted local transcript entry ID. The Claude transcript importer records that key, and history merge suppresses the imported cache-path row only when it exactly matches the local media-bearing turn. Genuine user-typed @path mentions outside the cache directories are untouched. Ambiguous rows, malformed markers, repeated candidates, and imported rows whose local counterpart no longer exists all fail open and remain visible.

Pre-marker Claude transcript rows cannot be correlated safely. They are intentionally retained, even when caption and timestamp resemble a local image turn, because inference could suppress a distinct user turn. This is a prospective exact-correlation fix rather than a migration or self-healing policy for legacy rows.

User Impact

New images sent to Claude CLI-backed conversations render as inline previews in chat history without a duplicate raw cache-path user row. Sessions whose local transcript was reset or lost keep their imported image turns visible. Existing pre-marker conversations retain their legacy raw-path rows until a separate loss-safe legacy policy exists.

Evidence

Live before/after on an isolated dev gateway

Procedure: isolated profile (--profile evd, own state dir, port 23117, never the operator gateway), model claude-cli/claude-sonnet-5. One real image turn sent through chat.send (the same RPC the composer uses); the Claude CLI ran, wrote the content-addressed cache image, recorded the @path-mutated prompt in its project JSONL, and the session got its claude-cli binding.

Before — gateway built from the PR's merge base (116f364b505): the imported CLI transcript row fails dedupe and renders as a duplicate user bubble with the raw cache filename link:

before

Target rendering — the correlated row is removed and the local media-bearing row renders as one user bubble with the inline thumbnail; the assistant reply remains intact:

after

These captures predate the final exact-correlation refinement. They demonstrate the original defect and target rendering, while current-head automated coverage proves marker-bearing suppression and intentional legacy-row retention. They do not claim that pre-marker histories self-heal.

Tests and checks

  • src/gateway/cli-session-history.test.ts covers exact producer-marker correlation, same-caption disambiguation, one-time candidate consumption, malformed markers, orphan retention, mention stripping in string/text-block content, and legacy captioned/cache-only rows retained beside nearby local media-bearing turns.
  • node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway.config.ts src/gateway/cli-session-history.test.ts — 198 passed across the gateway core/server/client projects.
  • node scripts/run-tsgo-core-test-shards.mjs src — clean; oxlint and oxfmt --check clean on changed files.
  • Mandatory uncommitted-diff autoreview after the legacy-retention test addition: clean, no accepted or actionable findings.

@clawsweeper

clawsweeper Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S maintainer Maintainer-authored PR labels Aug 26, 2026
@jalehman
jalehman marked this pull request as ready for review August 26, 2026 22:28
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 26, 2026
@clawsweeper

clawsweeper Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 28, 2026, 6:55 PM ET / 22:55 UTC.

ClawSweeper review

What this changes

The PR adds an opaque per-turn marker to Claude CLI image prompts and suppresses only the matching imported cache-path row when merging it with OpenClaw’s local image-bearing transcript row.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

No blocking correctness finding: the PR repairs the current-main duplicate-history path with exact local-turn correlation. It remains open for protected maintainer handling because it deliberately establishes prospective history-display policy for Claude CLI image turns.

Priority: P1
Reviewed head: 82b345f0fc95541a62fcdc3b866a1ef531705349
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is a focused, source-supported repair with meaningful boundary coverage and no blocking defect found.
Proof confidence 🌊 off-meta tidepool Not applicable: This is identified as a member-authored PR, so the external-contributor proof gate does not apply; the supplied isolated-Gateway before/after screenshots nonetheless support the claimed UI outcome, though this reviewer could not reopen the attachments because GitHub DNS was unavailable.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This is identified as a member-authored PR, so the external-contributor proof gate does not apply; the supplied isolated-Gateway before/after screenshots nonetheless support the claimed UI outcome, though this reviewer could not reopen the attachments because GitHub DNS was unavailable.
Evidence reviewed 6 items Current-main defect path: Current main imports bound Claude CLI JSONL and merges it with local messages; its merge implementation only compares normalized text and timestamps, so an appended cache-path suffix prevents a text match.
Exact owner-boundary repair: The runner derives a key only after the local transcript admission has an entry ID, and the importer records and removes the marker before the merge can compare it.
Fail-open merge behavior: A cache-path import is suppressed only after its marker matches a local message ID hash and that local media-bearing candidate is consumed once; unmatched, legacy, and repeated imports remain visible.
Findings None None.
Security None None.

How this fits together

The CLI runner converts inbound images to local paths for Claude CLI, which records the altered prompt in its JSONL history. Gateway history import then merges that external transcript with the local transcript before chat clients display it.

flowchart LR
  A[Inbound image turn] --> B[Local transcript row]
  A --> C[Claude CLI prompt]
  C --> D[Claude JSONL history]
  B --> E[History merge]
  D --> E
  E --> F[Gateway chat history]
Loading

Decision needed

Question Recommendation
Should OpenClaw adopt prospective-only marker correlation for Claude CLI image history, suppressing only exact local matches while retaining all legacy and orphaned imported rows? Accept exact prospective correlation: Approve the marker-based policy for new image turns and retain unmatched and pre-marker imported rows as visible history.

Why: The code proves the narrow behavior and avoids ambiguous deletion, but choosing this durable user-visible history policy requires owner intent.

Before merge

  • Resolve merge risk (P1) - Merging changes the display policy for new Claude CLI image turns: marker-bearing imports are intentionally hidden when their exact local media-bearing counterpart exists, while legacy and orphaned rows remain visible.
  • Resolve merge risk (P1) - This bug fix has production +209/-38 lines; the added correlation must span prompt production, external-history parsing, and merge ownership, so a net-neutral implementation would not preserve the required exact, fail-open boundary.
  • Complete next step (P2) - A protected maintainer-authored PR changes deliberate session-history display policy, so an owner must accept the prospective-only behavior before merge.
Agent review details

Security

None.

PR surface

Source +171, Tests +536. Total +707 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 5 209 38 +171
Tests 3 536 0 +536
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 745 38 +707

Review metrics

Metric Value Why it matters
Production versus tests production +209/-38 (net +171); tests +536/-0 The repair crosses prompt creation, external-history parsing, and merge ownership; the added tests cover the ambiguity and retention boundaries.

Stored data model

Persistent data-model change detected: serialized state: src/agents/cli-image-turn-correlation.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Accept the prospective history policy (recommended)
    Confirm that only exact marker-bearing duplicates may be hidden and that legacy or orphaned CLI rows must remain visible.
  2. Pause for a different policy
    Do not merge until an owner chooses a different correlation or legacy-history approach.

Technical review

Best possible solution:

Keep the exact prospective correlation design after an owner confirms that preserving legacy/orphaned rows while suppressing only new marker-bearing duplicates is the intended session-history policy.

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

Yes, source-reproducible: current main merges the altered Claude CLI prompt as a distinct user row, while the supplied isolated-Gateway scenario exercises that same path. This read-only review did not execute the scenario, and GitHub attachment retrieval was unavailable locally.

Is this the best way to solve the issue?

Yes, subject to the explicit history-policy decision: exact persisted-turn correlation is safer than parser-time deletion or text/timestamp inference because it preserves unmatched and pre-marker imports.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P1: The defect produces duplicate, misleading user rows in an active Claude CLI chat-history workflow.
  • merge-risk: 🚨 session-state: The PR intentionally changes which imported transcript rows appear in a session’s visible history.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is identified as a member-authored PR, so the external-contributor proof gate does not apply; the supplied isolated-Gateway before/after screenshots nonetheless support the claimed UI outcome, though this reviewer could not reopen the attachments because GitHub DNS was unavailable.

Evidence

What I checked:

  • Current-main defect path: Current main imports bound Claude CLI JSONL and merges it with local messages; its merge implementation only compares normalized text and timestamps, so an appended cache-path suffix prevents a text match. (src/gateway/cli-session-history.ts:49, 3c00dbc71bfe)
  • Exact owner-boundary repair: The runner derives a key only after the local transcript admission has an entry ID, and the importer records and removes the marker before the merge can compare it. (src/agents/cli-runner/execute.ts:181, 82b345f0fc95)
  • Fail-open merge behavior: A cache-path import is suppressed only after its marker matches a local message ID hash and that local media-bearing candidate is consumed once; unmatched, legacy, and repeated imports remain visible. (src/gateway/cli-session-history.merge.ts:278, 82b345f0fc95)
  • Boundary coverage: Focused tests cover exact correlation, cache-only turns, same-caption disambiguation, one-time candidate use, and retention when no matching local media turn survives. (src/gateway/cli-session-history.test.ts:588, 82b345f0fc95)
  • Feature-history provenance: Blame attributes the current import-and-merge call site to the recent shared-history work, establishing the current owner trail rather than attributing the defect to this proposed branch. (src/gateway/cli-session-history.ts:60, df905a6cb652)
  • Supplied behavior proof: The PR body supplies isolated-Gateway before/after screenshots for a real Claude CLI image turn and states that the final marker refinement is covered by the current-head tests. Attachment retrieval was unavailable because DNS could not resolve GitHub, which is a reviewer limitation rather than missing contributor evidence. (82b345f0fc95)

Likely related people:

  • Peter Steinberger: Current-main blame and the latest available history attribute the Claude CLI history import boundary to the shared-history repair that introduced this call path. (role: recent feature owner; confidence: high; commits: df905a6cb652; files: src/gateway/cli-session-history.ts, src/gateway/cli-session-history.merge.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Confirm the prospective-only Claude CLI history policy before merge.

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.

History

Review history (13 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-28T14:24:07.231Z sha 4514bf6 :: found issues before merge. :: [P1] Consume each local image match at most once
  • reviewed 2026-08-28T17:58:47.347Z sha 4516fe4 :: found issues before merge. :: [P1] Preserve captioned image turns when local history is absent
  • reviewed 2026-08-28T18:07:55.369Z sha 4516fe4 :: needs changes before merge. :: [P1] Preserve captioned image turns when local history is absent
  • reviewed 2026-08-28T20:05:48.106Z sha 3c93870 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T20:14:18.254Z sha 3c93870 :: needs changes before merge. :: [P1] Do not suppress cache-only imports on an ambiguous media match
  • reviewed 2026-08-28T21:08:45.083Z sha ef35b45 :: found issues before merge. :: [P1] Correlate cache-path imports with their originating user turn
  • reviewed 2026-08-28T22:14:10.626Z sha 62f0dc1ada1210ba6942b57d5d7a2e3f31e27d21 :: found issues before merge. :: [P1] Limit the self-healing claim to correlated image turns
  • reviewed 2026-08-28T22:31:57.564Z sha 62f0dc1ada1210ba6942b57d5d7a2e3f31e27d21 :: needs maintainer review before merge. :: none

@jalehman

Copy link
Copy Markdown
Contributor Author

Addressed the P1 in 09bbd3d with the recommended merge-time correlation: mention-only imported rows are no longer deleted at parse time. The importer keeps their original content and tags them cliImageMentionOnly; mergeImportedChatHistoryMessages suppresses a tagged row only when a local user row carrying image media facts falls within the existing 5-minute dedupe window, so reconstruction from the bound Claude JSONL with reset/lost local history retains the turn. Regression tests cover both branches (counterpart present → suppressed; absent → retained). PR body updated; the "stored data model" note is a false positive — the change is read-time only, nothing persisted changes format.

@jalehman

Copy link
Copy Markdown
Contributor Author

Live before/after UI evidence is now attached in the PR body: one real image turn on an isolated dev gateway (claude-cli/claude-sonnet-5, own profile/port), rendered by the merge-base build (duplicate raw cache-path row) and by this branch (single row with inline thumbnail) against the same session state. This closes the remaining evidence item; the capture also shows existing histories self-heal at read time.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed P2 Normal backlog priority with limited blast radius. labels Aug 27, 2026
@jalehman
jalehman force-pushed the fix/cli-image-history-mention-strip branch from 09bbd3d to 5ae6b20 Compare August 27, 2026 14:08
@jalehman
jalehman force-pushed the fix/cli-image-history-mention-strip branch from 5ae6b20 to a2ebc4c Compare August 27, 2026 22:52
@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Aug 27, 2026
@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 28, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 28, 2026
@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Aug 28, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 28, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 28, 2026
@jalehman
jalehman force-pushed the fix/cli-image-history-mention-strip branch from ef35b45 to 62f0dc1 Compare August 28, 2026 22:05
@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Aug 28, 2026
@clawsweeper

clawsweeper Bot commented Aug 28, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 28, 2026
…CLI user rows

The CLI runner appends @<.openclaw-cli-images path> mention lines to prompts
for backends that read images from disk. Claude Code records that mutated
prompt as its user message, so the transcript importer re-surfaced it as a
duplicate user row that failed text dedupe against the local row carrying the
media facts — showing inbound images as raw path links instead of previews.

Strip trailing image cache mention lines from imported user rows (string and
text-block content) and drop rows left empty, so imported rows dedupe into the
local row that already renders the thumbnail.
…ia merge-time correlation

Address ClawSweeper P1: the importer no longer drops image-only user rows at
parse time, where it cannot know whether a local media-bearing counterpart
survives. Mention-only rows keep their original content and are tagged with
__openclaw.cliImageMentionOnly; mergeImportedChatHistoryMessages suppresses a
tagged row only when a local user row carrying image media facts falls within
the existing dedupe timestamp window. With local history reset or lost, the
imported turn is retained instead of silently disappearing.
… safety ratchet

The assertion-safety ratchet flags uncommented non-const assertions beyond
each file's baseline. Narrow imported block and metadata access through
asOptionalRecord instead of inline casts; the one remaining cast into
normalizeMediaFacts carries its SAFETY invariant.
@jalehman
jalehman force-pushed the fix/cli-image-history-mention-strip branch from 62f0dc1 to 82b345f Compare August 28, 2026 22:46
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 28, 2026
@jalehman
jalehman merged commit 6f6b649 into main Aug 28, 2026
243 checks passed
@jalehman
jalehman deleted the fix/cli-image-history-mention-strip branch August 28, 2026 23:28
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 29, 2026
…th links in chat history (openclaw#130463)

* fix(gateway): strip CLI-injected image mentions from imported Claude CLI user rows

The CLI runner appends @<.openclaw-cli-images path> mention lines to prompts
for backends that read images from disk. Claude Code records that mutated
prompt as its user message, so the transcript importer re-surfaced it as a
duplicate user row that failed text dedupe against the local row carrying the
media facts — showing inbound images as raw path links instead of previews.

Strip trailing image cache mention lines from imported user rows (string and
text-block content) and drop rows left empty, so imported rows dedupe into the
local row that already renders the thumbnail.

* fix(gateway): preserve orphaned mention-only Claude CLI image turns via merge-time correlation

Address ClawSweeper P1: the importer no longer drops image-only user rows at
parse time, where it cannot know whether a local media-bearing counterpart
survives. Mention-only rows keep their original content and are tagged with
__openclaw.cliImageMentionOnly; mergeImportedChatHistoryMessages suppresses a
tagged row only when a local user row carrying image media facts falls within
the existing dedupe timestamp window. With local history reset or lost, the
imported turn is retained instead of silently disappearing.

* chore(gateway): replace new type assertions with record narrowing for safety ratchet

The assertion-safety ratchet flags uncommented non-const assertions beyond
each file's baseline. Narrow imported block and metadata access through
asOptionalRecord instead of inline casts; the one remaining cast into
normalizeMediaFacts carries its SAFETY invariant.

* fix(gateway): require image history timestamp correlation

* fix(gateway): consume image history matches once

* fix(gateway): preserve orphaned CLI image captions

* fix(gateway): retain ambiguous CLI image turns

* fix(gateway): correlate Claude image turns exactly

* test(gateway): document legacy image row retention
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

1 participant