Skip to content

Commit 39f0e8a

Browse files
committed
fix(cli): report failed message actions accurately
1 parent 424521a commit 39f0e8a

7 files changed

Lines changed: 180 additions & 24 deletions

File tree

‎src/cli/program/message/helpers.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
import { Command } from "commander";
33
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
44
import { beforeEach, describe, expect, it, vi } from "vitest";
5+
import { registerMessagePollCommand } from "./register.poll.js";
6+
import { registerMessageReactionsCommands } from "./register.reactions.js";
7+
import { registerMessageReadEditDeleteCommands } from "./register.read-edit-delete.js";
58
import { registerMessageSendCommand } from "./register.send.js";
69

710
const messageCommandMock = vi.fn(async (): Promise<unknown> => undefined);
@@ -212,6 +215,64 @@ describe("runMessageAction", () => {
212215
},
213216
);
214217

218+
it.each([
219+
["disabled reaction", "react", { ok: false, hint: "Reactions are disabled." }, 1],
220+
["rejected added reaction", "react", { ok: false, warning: "Unavailable", added: "✅" }, 1],
221+
["rejected delete", "delete", { ok: false, deleted: false, warning: "Not deleted" }, 1],
222+
["rejected poll", "poll", { ok: false, error: "Poll rejected" }, 1],
223+
["rejected send", "send", { ok: false, error: "Message rejected" }, 1],
224+
["successful reaction", "react", { ok: true, added: "✅" }, 0],
225+
["legacy reaction", "react", { added: "✅" }, 0],
226+
["non-boolean outcome", "react", { ok: "false", added: "✅" }, 0],
227+
["dry-run", "react", { ok: false, error: "Not executed" }, 0],
228+
] as const)(
229+
"propagates %s through the real CLI parser",
230+
async (name, action, payload, exitCode) => {
231+
const dryRun = name === "dry-run";
232+
const kind = action === "send" || action === "poll" ? action : "action";
233+
messageCommandMock.mockResolvedValueOnce({
234+
kind,
235+
channel: "telegram",
236+
action,
237+
...(kind === "action" ? {} : { to: "123" }),
238+
handledBy: "plugin",
239+
payload,
240+
dryRun,
241+
});
242+
const program = new Command();
243+
const message = program.command("message");
244+
const helpers = createMessageCliHelpers(message, "telegram");
245+
registerMessageSendCommand(message, helpers);
246+
registerMessagePollCommand(message, helpers);
247+
registerMessageReactionsCommands(message, helpers);
248+
registerMessageReadEditDeleteCommands(message, helpers);
249+
const args = {
250+
react: ["--message-id", "456", "--emoji", "✅"],
251+
delete: ["--message-id", "456"],
252+
poll: ["--poll-question", "Ready?", "--poll-option", "Yes", "--poll-option", "No"],
253+
send: ["--message", "hello"],
254+
}[action];
255+
256+
await expect(
257+
program.parseAsync(
258+
[
259+
"message",
260+
action,
261+
"--channel",
262+
"telegram",
263+
"--target",
264+
"123",
265+
...args,
266+
...(dryRun ? ["--dry-run"] : []),
267+
],
268+
{ from: "user" },
269+
),
270+
).rejects.toThrow("exit");
271+
272+
expect(exitMock).toHaveBeenCalledWith(exitCode);
273+
},
274+
);
275+
215276
it("loads configured channel plugins when no target channel is known yet", async () => {
216277
await runSendAction({ channel: undefined });
217278

‎src/cli/program/message/helpers.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { getRuntimeConfig } from "../../../config/config.js";
1515
import { danger, setVerbose } from "../../../globals.js";
1616
import { formatErrorMessage } from "../../../infra/errors.js";
1717
import { CHANNEL_TARGET_DESCRIPTION } from "../../../infra/outbound/channel-target.js";
18-
import { isMessageActionSuccessful } from "../../../infra/outbound/message-action-contracts.js";
18+
import { resolveMessageActionOutcome } from "../../../infra/outbound/message-action-contracts.js";
1919
import { withActivatedPluginIds } from "../../../plugins/activation-context.js";
2020
import {
2121
resolveConfiguredChannelPluginIds,
@@ -221,7 +221,7 @@ export function createMessageCliHelpers(
221221
if (!ACTIONS_WITHOUT_STOP_HOOKS.has(action)) {
222222
await withPluginRuntimeRegistryScope(pluginRegistry, runPluginStopHooks);
223223
}
224-
failed ||= result !== undefined && !isMessageActionSuccessful(result);
224+
failed ||= result !== undefined && !resolveMessageActionOutcome(result).ok;
225225
defaultRuntime.exit(failed ? 1 : 0);
226226
};
227227

‎src/commands/message-format.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,41 @@ describe("formatMessageCliText send results", () => {
294294
);
295295
});
296296

297+
describe("formatMessageCliText provider-reported failures", () => {
298+
it.each([
299+
["disabled reaction", "react", { ok: false, hint: "Reactions are disabled." }, "disabled"],
300+
[
301+
"rejected added reaction",
302+
"react",
303+
{ ok: false, warning: "Unavailable", added: "✅" },
304+
"Unavailable",
305+
],
306+
[
307+
"rejected delete",
308+
"delete",
309+
{ ok: false, deleted: false, warning: "Not deleted" },
310+
"Not deleted",
311+
],
312+
["rejected poll", "poll", { ok: false, error: "Poll rejected" }, "Poll rejected"],
313+
["rejected send", "send", { ok: false, error: "Message rejected" }, "Message rejected"],
314+
] as const)("reports %s without claiming success", (_name, action, payload, expected) => {
315+
const result = {
316+
kind: action === "send" || action === "poll" ? action : "action",
317+
channel: "telegram",
318+
action,
319+
to: "123",
320+
handledBy: "plugin",
321+
payload,
322+
dryRun: false,
323+
} as MessageActionResult;
324+
325+
const output = textJoined(formatMessageCliText(result));
326+
327+
expect(output).toContain(expected);
328+
expect(output).not.toContain("✅");
329+
});
330+
});
331+
297332
describe("formatMessageCliText poll results", () => {
298333
it("formats direct core poll results as direct deliveries", () => {
299334
const result = {

‎src/commands/message-format.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ import type { ChannelId } from "../channels/plugins/types.public.js";
88
import type { OutboundDeliveryResult } from "../infra/outbound/deliver.js";
99
import { formatGatewaySummary, formatOutboundDeliverySummary } from "../infra/outbound/format.js";
1010
import {
11-
isMessageActionSuccessful,
12-
resolveMessageSendOutcome,
11+
resolveMessageActionOutcome,
1312
type MessageActionResult,
1413
} from "../infra/outbound/message-action-contracts.js";
1514
import { formatTargetDisplay } from "../infra/outbound/target-resolver.js";
@@ -290,6 +289,7 @@ export function formatMessageCliText(
290289
return [muted(`[dry-run] would run ${result.action} via ${result.channel}`)];
291290
}
292291

292+
const outcome = resolveMessageActionOutcome(result);
293293
if (result.kind === "broadcast") {
294294
const results = result.payload.results ?? [];
295295
const rows = results.map((entry) => ({
@@ -300,7 +300,7 @@ export function formatMessageCliText(
300300
}));
301301
const okCount = results.filter((entry) => entry.ok).length;
302302
const total = results.length;
303-
const successful = isMessageActionSuccessful(result);
303+
const successful = outcome.ok;
304304
const headingLine = (successful ? ok : fail)(
305305
`${successful ? "✅ Broadcast complete" : "❌ Broadcast failed"} (${okCount}/${total} succeeded, ${total - okCount} failed)`,
306306
);
@@ -319,12 +319,12 @@ export function formatMessageCliText(
319319
];
320320
}
321321

322+
if (!outcome.ok) {
323+
const messageId = result.kind === "send" ? result.sendResult?.result?.messageId : undefined;
324+
return [fail(`❌ ${outcome.error}${messageId ? ` Message ID: ${messageId}` : ""}`)];
325+
}
326+
322327
if (result.kind === "send") {
323-
const outcome = resolveMessageSendOutcome(result.sendResult);
324-
if (!outcome.ok) {
325-
const messageId = result.sendResult?.result?.messageId;
326-
return [fail(`❌ ${outcome.error}${messageId ? ` Message ID: ${messageId}` : ""}`)];
327-
}
328328
if (result.handledBy === "core" && result.sendResult) {
329329
const send = result.sendResult;
330330
if (send.via === "direct") {

‎src/commands/message.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -665,6 +665,49 @@ describe("messageCommand", () => {
665665
},
666666
);
667667

668+
it.each([
669+
[
670+
"disabled reaction",
671+
"react",
672+
{ ok: false, hint: "Reactions are disabled." },
673+
"Reactions are disabled.",
674+
],
675+
[
676+
"rejected added reaction",
677+
"react",
678+
{ ok: false, warning: "Unavailable", added: "✅" },
679+
"Unavailable",
680+
],
681+
[
682+
"rejected delete",
683+
"delete",
684+
{ ok: false, deleted: false, warning: "Not deleted" },
685+
"Not deleted",
686+
],
687+
["rejected poll", "poll", { ok: false, error: "Poll rejected" }, "Poll rejected"],
688+
["rejected send", "send", { ok: false, error: "Message rejected" }, "Message rejected"],
689+
] as const)("reports %s truthfully in JSON output", async (_name, action, payload, expected) => {
690+
runMessageActionMock.mockResolvedValueOnce({
691+
kind: action === "send" || action === "poll" ? action : "action",
692+
channel: "telegram",
693+
action,
694+
to: "123456",
695+
handledBy: "plugin",
696+
payload,
697+
dryRun: false,
698+
} as MessageActionResult);
699+
700+
await runMessageCommand({ action });
701+
702+
const json = JSON.parse(String(vi.mocked(runtime.log).mock.calls[0]?.[0]));
703+
expect(json).toMatchObject({
704+
ok: false,
705+
error: { type: "cli_error", message: expected },
706+
});
707+
expect(json.payload).toEqual(payload);
708+
expect(json).not.toHaveProperty("deliveryStatus");
709+
});
710+
668711
it("rejects unknown message actions before dispatch", async () => {
669712
await expect(runMessageCommand({ action: "nope" })).rejects.toThrow("Unknown message action");
670713
expect(runMessageActionMock).not.toHaveBeenCalled();

‎src/commands/message.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,7 @@ import {
2424
resolveMessageBroadcastAccountPlan,
2525
validateExplicitMessageAccountSelection,
2626
} from "../infra/outbound/message-account-selection.js";
27-
import {
28-
isMessageActionSuccessful,
29-
resolveMessageSendOutcome,
30-
} from "../infra/outbound/message-action-contracts.js";
27+
import { resolveMessageActionOutcome } from "../infra/outbound/message-action-contracts.js";
3128
import { runMessageAction } from "../infra/outbound/message-action-runner.js";
3229
import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
3330

@@ -53,15 +50,15 @@ function extractMessageId(payload: unknown): string | undefined {
5350
function buildMessageCliJson(result: Awaited<ReturnType<typeof runMessageAction>>) {
5451
const messageId = extractMessageId(result.payload);
5552
const sendResult = result.kind === "send" ? result.sendResult : undefined;
56-
const sendOutcome = result.kind === "send" ? resolveMessageSendOutcome(sendResult) : undefined;
53+
const outcome = resolveMessageActionOutcome(result);
5754
return {
5855
...(result.kind === "broadcast"
59-
? { ok: isMessageActionSuccessful(result) }
60-
: sendOutcome && !sendOutcome.ok && !result.dryRun
56+
? { ok: outcome.ok }
57+
: !outcome.ok
6158
? {
62-
...formatCliJsonFailure(sendOutcome.error),
63-
deliveryStatus: sendResult?.deliveryStatus,
64-
...(sendOutcome.sentBeforeError ? { sentBeforeError: true } : {}),
59+
...formatCliJsonFailure(outcome.error),
60+
...(sendResult ? { deliveryStatus: sendResult.deliveryStatus } : {}),
61+
...(outcome.sentBeforeError ? { sentBeforeError: true } : {}),
6562
}
6663
: {}),
6764
action: result.action,

‎src/infra/outbound/message-action-contracts.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
2+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
13
import type { AgentToolResult } from "../../agents/runtime/index.js";
24
import type { ExecutionIdentityAdmissionToken } from "../../audit/execution-identity-admission.js";
35
import type { SourceReplyDeliveryMode } from "../../auto-reply/get-reply-options.types.js";
@@ -208,10 +210,28 @@ export function resolveMessageSendOutcome(
208210
return sendResult.deliveryStatus satisfies never;
209211
}
210212

211-
export const isMessageActionSuccessful = (result: MessageActionResult): boolean =>
212-
result.kind === "broadcast"
213-
? result.payload.results.every((entry) => entry.ok)
214-
: result.kind !== "send" || result.dryRun || resolveMessageSendOutcome(result.sendResult).ok;
213+
export function resolveMessageActionOutcome(
214+
result: MessageActionResult,
215+
): ReturnType<typeof resolveMessageSendOutcome> {
216+
if (result.kind === "broadcast") {
217+
const failure = result.payload.results.find((entry) => !entry.ok);
218+
return failure ? { ok: false, error: failure.error ?? "Broadcast failed." } : { ok: true };
219+
}
220+
if (result.dryRun) {
221+
return { ok: true };
222+
}
223+
const outcome =
224+
result.kind === "send" ? resolveMessageSendOutcome(result.sendResult) : { ok: true as const };
225+
const payload = result.payload;
226+
if (!outcome.ok || !isRecord(payload) || payload.ok !== false) {
227+
return outcome;
228+
}
229+
const error =
230+
[payload.error, payload.warning, payload.hint, payload.reason]
231+
.map(normalizeOptionalString)
232+
.find(Boolean) ?? `Message ${result.action} failed.`;
233+
return { ok: false, error };
234+
}
215235

216236
export type ResolvedActionContext = {
217237
cfg: OpenClawConfig;

0 commit comments

Comments
 (0)