Skip to content

Commit 68c78c4

Browse files
fix: deliver tool result media when verbose is off (#16679)
Merged via /review-pr -> /prepare-pr -> /merge-pr. Prepared head SHA: 6e16feb Co-authored-by: christianklotz <[email protected]> Co-authored-by: christianklotz <[email protected]> Reviewed-by: @christianklotz
1 parent 906c32d commit 68c78c4

6 files changed

Lines changed: 393 additions & 0 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Docs: https://docs.openclaw.ai
1414

1515
### Fixes
1616

17+
- Agents: deliver tool result media (screenshots, images, audio) to channels regardless of verbose level. (#11735) Thanks @strelov1.
1718
- Telegram: when `channels.telegram.commands.native` is `false`, exclude plugin commands from `setMyCommands` menu registration while keeping plugin slash handlers callable. (#15132) Thanks @Glucksberg.
1819
- LINE: return 200 OK for Developers Console "Verify" requests (`{"events":[]}`) without `X-Line-Signature`, while still requiring signatures for real deliveries. (#16582) Thanks @arosstale.
1920
- Cron: deliver text-only output directly when `delivery.to` is set so cron recipients get full output instead of summaries. (#16360) Thanks @thewilloftheshadow.
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import type { EmbeddedPiSubscribeContext } from "./pi-embedded-subscribe.handlers.types.js";
3+
import { handleToolExecutionEnd } from "./pi-embedded-subscribe.handlers.tools.js";
4+
5+
// Minimal mock context factory. Only the fields needed for the media emission path.
6+
function createMockContext(overrides?: {
7+
shouldEmitToolOutput?: boolean;
8+
onToolResult?: ReturnType<typeof vi.fn>;
9+
}): EmbeddedPiSubscribeContext {
10+
const onToolResult = overrides?.onToolResult ?? vi.fn();
11+
return {
12+
params: {
13+
runId: "test-run",
14+
onToolResult,
15+
onAgentEvent: vi.fn(),
16+
},
17+
state: {
18+
toolMetaById: new Map(),
19+
toolMetas: [],
20+
toolSummaryById: new Set(),
21+
pendingMessagingTexts: new Map(),
22+
pendingMessagingTargets: new Map(),
23+
messagingToolSentTexts: [],
24+
messagingToolSentTextsNormalized: [],
25+
messagingToolSentTargets: [],
26+
},
27+
log: { debug: vi.fn(), warn: vi.fn() },
28+
shouldEmitToolResult: vi.fn(() => false),
29+
shouldEmitToolOutput: vi.fn(() => overrides?.shouldEmitToolOutput ?? false),
30+
emitToolSummary: vi.fn(),
31+
emitToolOutput: vi.fn(),
32+
trimMessagingToolSent: vi.fn(),
33+
hookRunner: undefined,
34+
// Fill in remaining required fields with no-ops.
35+
blockChunker: null,
36+
noteLastAssistant: vi.fn(),
37+
stripBlockTags: vi.fn((t: string) => t),
38+
emitBlockChunk: vi.fn(),
39+
flushBlockReplyBuffer: vi.fn(),
40+
emitReasoningStream: vi.fn(),
41+
consumeReplyDirectives: vi.fn(() => null),
42+
consumePartialReplyDirectives: vi.fn(() => null),
43+
resetAssistantMessageState: vi.fn(),
44+
resetForCompactionRetry: vi.fn(),
45+
finalizeAssistantTexts: vi.fn(),
46+
ensureCompactionPromise: vi.fn(),
47+
noteCompactionRetry: vi.fn(),
48+
resolveCompactionRetry: vi.fn(),
49+
maybeResolveCompactionWait: vi.fn(),
50+
recordAssistantUsage: vi.fn(),
51+
incrementCompactionCount: vi.fn(),
52+
getUsageTotals: vi.fn(() => undefined),
53+
getCompactionCount: vi.fn(() => 0),
54+
} as unknown as EmbeddedPiSubscribeContext;
55+
}
56+
57+
describe("handleToolExecutionEnd media emission", () => {
58+
it("emits media when verbose is off and tool result has MEDIA: path", async () => {
59+
const onToolResult = vi.fn();
60+
const ctx = createMockContext({ shouldEmitToolOutput: false, onToolResult });
61+
62+
await handleToolExecutionEnd(ctx, {
63+
type: "tool_execution_end",
64+
toolName: "browser",
65+
toolCallId: "tc-1",
66+
isError: false,
67+
result: {
68+
content: [
69+
{ type: "text", text: "MEDIA:/tmp/screenshot.png" },
70+
{ type: "image", data: "base64", mimeType: "image/png" },
71+
],
72+
details: { path: "/tmp/screenshot.png" },
73+
},
74+
});
75+
76+
expect(onToolResult).toHaveBeenCalledWith({
77+
mediaUrls: ["/tmp/screenshot.png"],
78+
});
79+
});
80+
81+
it("does NOT emit media when verbose is full (emitToolOutput handles it)", async () => {
82+
const onToolResult = vi.fn();
83+
const ctx = createMockContext({ shouldEmitToolOutput: true, onToolResult });
84+
85+
await handleToolExecutionEnd(ctx, {
86+
type: "tool_execution_end",
87+
toolName: "browser",
88+
toolCallId: "tc-1",
89+
isError: false,
90+
result: {
91+
content: [
92+
{ type: "text", text: "MEDIA:/tmp/screenshot.png" },
93+
{ type: "image", data: "base64", mimeType: "image/png" },
94+
],
95+
details: { path: "/tmp/screenshot.png" },
96+
},
97+
});
98+
99+
// onToolResult should NOT be called by the new media path (emitToolOutput handles it).
100+
// It may be called by emitToolOutput, but the new block should not fire.
101+
// Verify emitToolOutput was called instead.
102+
expect(ctx.emitToolOutput).toHaveBeenCalled();
103+
// The direct media emission should not have been called with just mediaUrls.
104+
const directMediaCalls = onToolResult.mock.calls.filter(
105+
(call: unknown[]) =>
106+
call[0] &&
107+
typeof call[0] === "object" &&
108+
"mediaUrls" in (call[0] as Record<string, unknown>) &&
109+
!("text" in (call[0] as Record<string, unknown>)),
110+
);
111+
expect(directMediaCalls).toHaveLength(0);
112+
});
113+
114+
it("does NOT emit media for error results", async () => {
115+
const onToolResult = vi.fn();
116+
const ctx = createMockContext({ shouldEmitToolOutput: false, onToolResult });
117+
118+
await handleToolExecutionEnd(ctx, {
119+
type: "tool_execution_end",
120+
toolName: "browser",
121+
toolCallId: "tc-1",
122+
isError: true,
123+
result: {
124+
content: [
125+
{ type: "text", text: "MEDIA:/tmp/screenshot.png" },
126+
{ type: "image", data: "base64", mimeType: "image/png" },
127+
],
128+
details: { path: "/tmp/screenshot.png" },
129+
},
130+
});
131+
132+
expect(onToolResult).not.toHaveBeenCalled();
133+
});
134+
135+
it("does NOT emit when tool result has no media", async () => {
136+
const onToolResult = vi.fn();
137+
const ctx = createMockContext({ shouldEmitToolOutput: false, onToolResult });
138+
139+
await handleToolExecutionEnd(ctx, {
140+
type: "tool_execution_end",
141+
toolName: "bash",
142+
toolCallId: "tc-1",
143+
isError: false,
144+
result: {
145+
content: [{ type: "text", text: "Command executed successfully" }],
146+
},
147+
});
148+
149+
expect(onToolResult).not.toHaveBeenCalled();
150+
});
151+
152+
it("emits media from details.path fallback when no MEDIA: text", async () => {
153+
const onToolResult = vi.fn();
154+
const ctx = createMockContext({ shouldEmitToolOutput: false, onToolResult });
155+
156+
await handleToolExecutionEnd(ctx, {
157+
type: "tool_execution_end",
158+
toolName: "canvas",
159+
toolCallId: "tc-1",
160+
isError: false,
161+
result: {
162+
content: [
163+
{ type: "text", text: "Rendered canvas" },
164+
{ type: "image", data: "base64", mimeType: "image/png" },
165+
],
166+
details: { path: "/tmp/canvas-output.png" },
167+
},
168+
});
169+
170+
expect(onToolResult).toHaveBeenCalledWith({
171+
mediaUrls: ["/tmp/canvas-output.png"],
172+
});
173+
});
174+
});

‎src/agents/pi-embedded-subscribe.handlers.tools.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { normalizeTextForComparison } from "./pi-embedded-helpers.js";
1010
import { isMessagingTool, isMessagingToolSendAction } from "./pi-embedded-messaging.js";
1111
import {
1212
extractToolErrorMessage,
13+
extractToolResultMediaPaths,
1314
extractToolResultText,
1415
extractMessagingToolSend,
1516
isToolResultError,
@@ -266,6 +267,20 @@ export async function handleToolExecutionEnd(
266267
}
267268
}
268269

270+
// Deliver media from tool results when the verbose emitToolOutput path is off.
271+
// When shouldEmitToolOutput() is true, emitToolOutput already delivers media
272+
// via parseReplyDirectives (MEDIA: text extraction), so skip to avoid duplicates.
273+
if (ctx.params.onToolResult && !isToolError && !ctx.shouldEmitToolOutput()) {
274+
const mediaPaths = extractToolResultMediaPaths(result);
275+
if (mediaPaths.length > 0) {
276+
try {
277+
void ctx.params.onToolResult({ mediaUrls: mediaPaths });
278+
} catch {
279+
// ignore delivery failures
280+
}
281+
}
282+
}
283+
269284
// Run after_tool_call plugin hook (fire-and-forget)
270285
const hookRunnerAfter = ctx.hookRunner ?? getGlobalHookRunner();
271286
if (hookRunnerAfter?.hasHooks("after_tool_call")) {
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import { describe, expect, it } from "vitest";
2+
import { extractToolResultMediaPaths } from "./pi-embedded-subscribe.tools.js";
3+
4+
describe("extractToolResultMediaPaths", () => {
5+
it("returns empty array for null/undefined", () => {
6+
expect(extractToolResultMediaPaths(null)).toEqual([]);
7+
expect(extractToolResultMediaPaths(undefined)).toEqual([]);
8+
});
9+
10+
it("returns empty array for non-object", () => {
11+
expect(extractToolResultMediaPaths("hello")).toEqual([]);
12+
expect(extractToolResultMediaPaths(42)).toEqual([]);
13+
});
14+
15+
it("returns empty array when content is missing", () => {
16+
expect(extractToolResultMediaPaths({ details: { path: "/tmp/img.png" } })).toEqual([]);
17+
});
18+
19+
it("returns empty array when content has no text or image blocks", () => {
20+
expect(extractToolResultMediaPaths({ content: [{ type: "other" }] })).toEqual([]);
21+
});
22+
23+
it("extracts MEDIA: path from text content block", () => {
24+
const result = {
25+
content: [
26+
{ type: "text", text: "MEDIA:/tmp/screenshot.png" },
27+
{ type: "image", data: "base64data", mimeType: "image/png" },
28+
],
29+
details: { path: "/tmp/screenshot.png" },
30+
};
31+
expect(extractToolResultMediaPaths(result)).toEqual(["/tmp/screenshot.png"]);
32+
});
33+
34+
it("extracts MEDIA: path with extra text in the block", () => {
35+
const result = {
36+
content: [{ type: "text", text: "Here is the image\nMEDIA:/tmp/output.jpg\nDone" }],
37+
};
38+
expect(extractToolResultMediaPaths(result)).toEqual(["/tmp/output.jpg"]);
39+
});
40+
41+
it("extracts multiple MEDIA: paths from different text blocks", () => {
42+
const result = {
43+
content: [
44+
{ type: "text", text: "MEDIA:/tmp/page1.png" },
45+
{ type: "text", text: "MEDIA:/tmp/page2.png" },
46+
],
47+
};
48+
expect(extractToolResultMediaPaths(result)).toEqual(["/tmp/page1.png", "/tmp/page2.png"]);
49+
});
50+
51+
it("falls back to details.path when image content exists but no MEDIA: text", () => {
52+
// Pi SDK read tool doesn't include MEDIA: but OpenClaw imageResult
53+
// sets details.path as fallback.
54+
const result = {
55+
content: [
56+
{ type: "text", text: "Read image file [image/png]" },
57+
{ type: "image", data: "base64data", mimeType: "image/png" },
58+
],
59+
details: { path: "/tmp/generated.png" },
60+
};
61+
expect(extractToolResultMediaPaths(result)).toEqual(["/tmp/generated.png"]);
62+
});
63+
64+
it("returns empty array when image content exists but no MEDIA: and no details.path", () => {
65+
// Pi SDK read tool: has image content but no path anywhere in the result.
66+
const result = {
67+
content: [
68+
{ type: "text", text: "Read image file [image/png]" },
69+
{ type: "image", data: "base64data", mimeType: "image/png" },
70+
],
71+
};
72+
expect(extractToolResultMediaPaths(result)).toEqual([]);
73+
});
74+
75+
it("does not fall back to details.path when MEDIA: paths are found", () => {
76+
const result = {
77+
content: [
78+
{ type: "text", text: "MEDIA:/tmp/from-text.png" },
79+
{ type: "image", data: "base64data", mimeType: "image/png" },
80+
],
81+
details: { path: "/tmp/from-details.png" },
82+
};
83+
// MEDIA: text takes priority; details.path is NOT also included.
84+
expect(extractToolResultMediaPaths(result)).toEqual(["/tmp/from-text.png"]);
85+
});
86+
87+
it("handles backtick-wrapped MEDIA: paths", () => {
88+
const result = {
89+
content: [{ type: "text", text: "MEDIA: `/tmp/screenshot.png`" }],
90+
};
91+
expect(extractToolResultMediaPaths(result)).toEqual(["/tmp/screenshot.png"]);
92+
});
93+
94+
it("ignores null/undefined items in content array", () => {
95+
const result = {
96+
content: [null, undefined, { type: "text", text: "MEDIA:/tmp/ok.png" }],
97+
};
98+
expect(extractToolResultMediaPaths(result)).toEqual(["/tmp/ok.png"]);
99+
});
100+
101+
it("returns empty array for text-only results without MEDIA:", () => {
102+
const result = {
103+
content: [{ type: "text", text: "Command executed successfully" }],
104+
};
105+
expect(extractToolResultMediaPaths(result)).toEqual([]);
106+
});
107+
108+
it("ignores details.path when no image content exists", () => {
109+
// details.path without image content is not media.
110+
const result = {
111+
content: [{ type: "text", text: "File saved" }],
112+
details: { path: "/tmp/data.json" },
113+
};
114+
expect(extractToolResultMediaPaths(result)).toEqual([]);
115+
});
116+
117+
it("handles details.path with whitespace", () => {
118+
const result = {
119+
content: [{ type: "image", data: "base64", mimeType: "image/png" }],
120+
details: { path: " /tmp/image.png " },
121+
};
122+
expect(extractToolResultMediaPaths(result)).toEqual(["/tmp/image.png"]);
123+
});
124+
125+
it("skips empty details.path", () => {
126+
const result = {
127+
content: [{ type: "image", data: "base64", mimeType: "image/png" }],
128+
details: { path: " " },
129+
};
130+
expect(extractToolResultMediaPaths(result)).toEqual([]);
131+
});
132+
});

0 commit comments

Comments
 (0)