Skip to content

Commit 6f6b649

Browse files
authored
fix(gateway): images sent to Claude CLI sessions show as raw cache-path links in chat history (#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
1 parent f661f01 commit 6f6b649

8 files changed

Lines changed: 745 additions & 38 deletions
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { createHash } from "node:crypto";
2+
import { markInboundContextLabel } from "../auto-reply/reply/inbound-context-marker.js";
3+
4+
const CLI_IMAGE_TURN_LABEL = "Image turn:";
5+
const CLI_IMAGE_TURN_HEADER = markInboundContextLabel(CLI_IMAGE_TURN_LABEL);
6+
// Only a complete producer block is correlation evidence. Conflicting or
7+
// malformed copies must fail open so history merge cannot hide a real turn.
8+
const CLI_IMAGE_TURN_BLOCK_PATTERN = new RegExp(
9+
`${CLI_IMAGE_TURN_HEADER}\\n\`\`\`json\\n\\{"turnKey":"([a-f0-9]{64})"\\}\\n\`\`\``,
10+
"g",
11+
);
12+
13+
export function hashCliImageTurnEntryId(entryId: string): string {
14+
return createHash("sha256").update(entryId).digest("hex");
15+
}
16+
17+
export function formatCliImageTurnContext(turnKey: string): string {
18+
return `${CLI_IMAGE_TURN_HEADER}\n\`\`\`json\n${JSON.stringify({ turnKey })}\n\`\`\``;
19+
}
20+
21+
export function readCliImageTurnContext(text: string): string | undefined {
22+
const keys = Array.from(text.matchAll(CLI_IMAGE_TURN_BLOCK_PATTERN), (match) => match[1]);
23+
if (keys.length !== text.split(CLI_IMAGE_TURN_HEADER).length - 1) {
24+
return undefined;
25+
}
26+
const first = keys[0];
27+
return first && keys.every((key) => key === first) ? first : undefined;
28+
}
29+
30+
export function stripCliImageTurnContext(text: string, turnKey: string): string {
31+
const block = formatCliImageTurnContext(turnKey);
32+
return text
33+
.replace(`\n\n${block}\n\n`, "\n\n")
34+
.replace(`${block}\n\n`, "")
35+
.replace(`\n\n${block}`, "");
36+
}

‎src/agents/cli-runner.helpers.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,16 @@ import type { ImageContent } from "openclaw/plugin-sdk/llm";
88
import { beforeEach, describe, expect, it, vi } from "vitest";
99
import { createSolidPngBuffer } from "../../test/helpers/image-fixtures.js";
1010
import { buildInboundMediaNoteProjection } from "../auto-reply/media-note.js";
11+
import { stripInboundMetadata } from "../auto-reply/reply/strip-inbound-meta.js";
1112
import { resolvePreferredOpenClawTmpDir } from "../infra/tmp-openclaw-dir.js";
1213
import { getAgentScopedMediaLocalRoots } from "../media/local-roots.js";
1314
import { escapeRegExp } from "../shared/regexp.js";
1415
import { captureEnv, setTestEnvValue } from "../test-utils/env.js";
16+
import {
17+
formatCliImageTurnContext,
18+
hashCliImageTurnEntryId,
19+
readCliImageTurnContext,
20+
} from "./cli-image-turn-correlation.js";
1521
import {
1622
buildCliArgs,
1723
prepareCliPromptImagePayload,
@@ -421,6 +427,41 @@ describe("writeCliImages", () => {
421427
}
422428
});
423429

430+
it("carries exact image-turn correlation beside Claude prompt paths", async () => {
431+
const turnKey = hashCliImageTurnEntryId("transcript-entry-1");
432+
const prepared = await prepareCliPromptImagePayload({
433+
backend: { command: "claude", imageArg: "@" },
434+
prompt: "describe this",
435+
workspaceDir: "/workspace",
436+
images: [{ type: "image", data: "aW1hZ2U=", mimeType: "image/png" }],
437+
imageTurnKey: turnKey,
438+
});
439+
440+
try {
441+
expect(readCliImageTurnContext(prepared.prompt)).toBe(turnKey);
442+
expect(stripInboundMetadata(prepared.prompt)).not.toContain(turnKey);
443+
expect(stripInboundMetadata(prepared.prompt)).toContain(
444+
`@${expectDefined(prepared.imagePaths?.[0], "correlated image path")}`,
445+
);
446+
} finally {
447+
await fs.rm(expectDefined(prepared.imagePaths?.[0], "correlated image path"), {
448+
force: true,
449+
});
450+
}
451+
});
452+
453+
it("rejects conflicting or malformed image-turn correlation", () => {
454+
const first = hashCliImageTurnEntryId("transcript-entry-1");
455+
const second = hashCliImageTurnEntryId("transcript-entry-2");
456+
457+
expect(
458+
readCliImageTurnContext(
459+
`${formatCliImageTurnContext(first)}\n\n${formatCliImageTurnContext(second)}`,
460+
),
461+
).toBeUndefined();
462+
expect(readCliImageTurnContext(formatCliImageTurnContext("not-a-key"))).toBeUndefined();
463+
});
464+
424465
it("uses the shared media extension map for image formats beyond the tiny builtin list", async () => {
425466
const workspaceDir = await fs.mkdtemp(
426467
path.join(resolvePreferredOpenClawTmpDir(), "openclaw-cli-write-heic-"),

‎src/agents/cli-runner/execute.supervisor-capture.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ import {
1818
} from "../../infra/diagnostic-events.js";
1919
import type { CliBackendParseJsonlEvent } from "../../plugins/cli-backend.types.js";
2020
import type { getProcessSupervisor } from "../../process/supervisor/index.js";
21+
import { createUserTurnTranscriptRecorder } from "../../sessions/user-turn-transcript.js";
22+
import { createTestUserTurnTranscriptTarget } from "../../sessions/user-turn-transcript.test-support.js";
2123
import { createTestAdmittedRunContext } from "../admitted-run-context.test-support.js";
24+
import { hashCliImageTurnEntryId } from "../cli-image-turn-correlation.js";
2225
import { findCliMaxTurnsError } from "../failover-error.js";
2326
import { getCliMessagingDeliveryEvidence } from "./delivery-evidence.js";
2427
import { executePreparedCliRun } from "./execute.js";
@@ -150,6 +153,58 @@ beforeEach(() => {
150153
});
151154

152155
describe("executePreparedCliRun supervisor output capture", () => {
156+
it("binds Claude image prompts to the persisted local transcript turn", async () => {
157+
const entryId = "persisted-image-turn";
158+
const recorder = createUserTurnTranscriptRecorder({
159+
input: { text: "describe this" },
160+
target: createTestUserTurnTranscriptTarget(),
161+
});
162+
const message = recorder.message;
163+
if (!message) {
164+
throw new Error("expected prepared user turn");
165+
}
166+
recorder.markRuntimePersisted(message, {
167+
agentId: "main",
168+
sessionId: "session-1",
169+
sessionKey: "agent:main:main",
170+
storePath: "/tmp/sessions.db",
171+
generation: "generation-1",
172+
entryId,
173+
rawSeq: 1,
174+
effectiveParentId: null,
175+
activeMessagePosition: 0,
176+
logicalTurnId: "logical-turn-1",
177+
role: "user",
178+
});
179+
const context = buildPreparedCliRunContext({ output: "text", provider: "claude-cli" });
180+
context.preparedBackend.backend.imageArg = "@";
181+
context.params.userTurnTranscriptRecorder = recorder;
182+
context.params.images = [{ type: "image", data: "aW1hZ2U=", mimeType: "image/png" }];
183+
supervisorSpawnMock.mockImplementationOnce(async (...args: unknown[]) => {
184+
const input = args[0] as SupervisorSpawnInput;
185+
input.onStdout?.("done");
186+
return createManagedRun({
187+
reason: "exit",
188+
exitCode: 0,
189+
exitSignal: null,
190+
durationMs: 50,
191+
stdout: "",
192+
stderr: "",
193+
timedOut: false,
194+
noOutputTimedOut: false,
195+
});
196+
});
197+
198+
await executePreparedCliRun(context);
199+
200+
const spawnInput = requireSupervisorSpawnInput();
201+
if (!("input" in spawnInput)) {
202+
throw new Error("expected direct CLI process input");
203+
}
204+
const prompt = spawnInput.input;
205+
expect(prompt).toContain(hashCliImageTurnEntryId(entryId));
206+
});
207+
153208
it("passes native compaction as an argument and requires backend acknowledgement", async () => {
154209
const raw = `${JSON.stringify({ type: "system", subtype: "compacting" })}\n`;
155210
supervisorSpawnMock.mockImplementationOnce(async (...args: unknown[]) => {

‎src/agents/cli-runner/execute.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
resolveCliRuntimeOwnerFingerprint,
1515
} from "../cli-auth-epoch.js";
1616
import { resolveCliExecutableIdentity } from "../cli-executable-identity.js";
17+
import { hashCliImageTurnEntryId } from "../cli-image-turn-correlation.js";
1718
import type { CliOutput } from "../cli-output-contracts.js";
1819
import {
1920
detectImageReferences,
@@ -48,6 +49,7 @@ import { createCliToolTracking } from "./execute-tool-tracking.js";
4849
import {
4950
buildCliArgs,
5051
enqueueCliRun,
52+
isClaudeCliBackendId,
5153
prepareCliPromptImagePayload,
5254
resolveCliNoOutputTimeoutMs,
5355
resolveCliRunQueueKey,
@@ -176,6 +178,9 @@ export async function executePreparedCliRun(
176178
) {
177179
throw new Error("paired-node Claude CLI sessions do not support attachments or images");
178180
}
181+
const imageTurnEntryId = isClaudeCliBackendId(context.backendResolved.id)
182+
? params.userTurnTranscriptRecorder?.getAdmissionReceipt()?.entryId
183+
: undefined;
179184
const imagePayload = nodePlacement
180185
? { prompt, imagePaths: [] as string[], cleanupImages: async () => {} }
181186
: await prepareCliPromptImagePayload({
@@ -188,6 +193,7 @@ export async function executePreparedCliRun(
188193
imageOrder: params.imageOrder,
189194
mediaImageLayout: params.mediaImageLayout,
190195
media: params.media,
196+
...(imageTurnEntryId ? { imageTurnKey: hashCliImageTurnEntryId(imageTurnEntryId) } : {}),
191197
});
192198
prompt = imagePayload.prompt;
193199
const promptInputBackend =

‎src/agents/cli-runner/helpers.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { KeyedAsyncQueue } from "../../plugin-sdk/keyed-async-queue.js";
2929
import type { CliBackendConfig } from "../../plugins/cli-backend.types.js";
3030
import { listRegisteredPluginAgentPromptGuidance } from "../../plugins/command-registry-state.js";
3131
import type { BootstrapMode } from "../bootstrap-mode.js";
32+
import { formatCliImageTurnContext } from "../cli-image-turn-correlation.js";
3233
import type { EmbeddedContextFile } from "../embedded-agent-helpers.js";
3334
import {
3435
detectAndLoadPromptImages,
@@ -393,6 +394,7 @@ export async function prepareCliPromptImagePayload(params: {
393394
imageOrder?: PromptImageOrderEntry[];
394395
mediaImageLayout?: MediaImageLayout;
395396
media?: MediaFact[];
397+
imageTurnKey?: string;
396398
}): Promise<{
397399
prompt: string;
398400
imagePaths?: string[];
@@ -438,6 +440,9 @@ export async function prepareCliPromptImagePayload(params: {
438440
params.backend.input === "stdin" ||
439441
params.backend.imageArg === "@"
440442
) {
443+
if (params.imageTurnKey) {
444+
prompt = `${prompt.trimEnd()}\n\n${formatCliImageTurnContext(params.imageTurnKey)}`;
445+
}
441446
prompt = appendImagePathsToPrompt(
442447
prompt,
443448
imagePaths,

‎src/gateway/cli-session-history.claude.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ import {
88
parseDateStringTimestampMs,
99
} from "@openclaw/normalization-core/number-coercion";
1010
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
11+
import {
12+
readCliImageTurnContext,
13+
stripCliImageTurnContext,
14+
} from "../agents/cli-image-turn-correlation.js";
1115
import { hashCliReseedPrompt, parseCliReseedPrompt } from "../agents/cli-runner/reseed-envelope.js";
1216
import type { AgentMessage } from "../agents/runtime/index.js";
1317
import { redactTranscriptMessage } from "../agents/transcript-redact.js";
@@ -408,6 +412,11 @@ export function parseClaudeCliHistoryEntry(
408412
}
409413
}
410414
}
415+
const cliImageTurnKey =
416+
typeof content === "string" ? readCliImageTurnContext(content) : undefined;
417+
if (cliImageTurnKey && typeof content === "string") {
418+
content = stripCliImageTurnContext(content, cliImageTurnKey);
419+
}
411420
// Record provenance here, where the native flags are known, so downstream
412421
// display never has to infer operator authorship from message text.
413422
const harnessInjected = isClaudeCliVisibleHarnessContext(entry);
@@ -420,7 +429,7 @@ export function parseClaudeCliHistoryEntry(
420429
: {}),
421430
...(timestamp !== undefined ? { timestamp } : {}),
422431
},
423-
baseMeta,
432+
{ ...baseMeta, ...(cliImageTurnKey ? { cliImageTurnKey } : {}) },
424433
) as TranscriptLikeMessage;
425434
}
426435

0 commit comments

Comments
 (0)