Skip to content

Commit 452e734

Browse files
authored
fix(cli): unsuccessful message sends report success (#129202)
* fix(cli): report unsuccessful message sends accurately * fix(cli): preserve narrowed send result for failure JSON * chore(pr): leave release-owned changelog unchanged
1 parent 15826de commit 452e734

9 files changed

Lines changed: 245 additions & 43 deletions

File tree

‎docs/cli/message.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,11 @@ true}`. `--pin` is shorthand for pinned delivery when the channel supports
104104
- `--silent` (Telegram, Discord): send without a notification.
105105
- `--gif-playback` (WhatsApp only): treat video media as GIF playback.
106106

107+
When a send is suppressed by a message hook, fails, or only partially succeeds,
108+
the command explains the outcome and exits nonzero. Partial delivery keeps any
109+
confirmed message ID. JSON failures include `ok: false`, `deliveryStatus`, and
110+
`error`; successful JSON responses retain their existing shape.
111+
107112
```bash
108113
openclaw message send --channel discord \
109114
--target channel:123 --message "Choose:" \

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Message program helper tests cover message command helper behavior and mocks.
2+
import { Command } from "commander";
23
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
34
import { beforeEach, describe, expect, it, vi } from "vitest";
5+
import { registerMessageSendCommand } from "./register.send.js";
46

57
const messageCommandMock = vi.fn(async (): Promise<unknown> => undefined);
68
vi.mock("../../../commands/message.js", () => ({
@@ -150,6 +152,66 @@ describe("runMessageAction", () => {
150152
expect(exitMock).toHaveBeenCalledWith(0);
151153
});
152154

155+
it.each([
156+
{ name: "sent", status: "sent" as const, exitCode: 0 },
157+
{ name: "suppressed", status: "suppressed" as const, exitCode: 1 },
158+
{ name: "failed", status: "failed" as const, exitCode: 1 },
159+
{ name: "partial_failed", status: "partial_failed" as const, exitCode: 1 },
160+
{ name: "dry-run", status: undefined, dryRun: true, exitCode: 0 },
161+
])(
162+
"propagates $name send outcomes through the real CLI parser",
163+
async ({ status, dryRun, exitCode }) => {
164+
const sendResult = {
165+
channel: "discord",
166+
to: "channel:123",
167+
via: "direct" as const,
168+
mediaUrl: null,
169+
...(status ? { deliveryStatus: status } : {}),
170+
...(status === "suppressed"
171+
? { suppressionReason: "cancelled_by_message_sending_hook" as const }
172+
: {}),
173+
...(status === "failed" || status === "partial_failed"
174+
? { error: "provider rejected the message" }
175+
: {}),
176+
...(status === "partial_failed"
177+
? { sentBeforeError: true as const, result: { channel: "discord", messageId: "part-1" } }
178+
: {}),
179+
};
180+
messageCommandMock.mockResolvedValueOnce({
181+
kind: "send",
182+
channel: "discord",
183+
action: "send",
184+
to: "channel:123",
185+
handledBy: "core",
186+
payload: sendResult,
187+
sendResult,
188+
dryRun: Boolean(dryRun),
189+
});
190+
const program = new Command();
191+
const message = program.command("message");
192+
registerMessageSendCommand(message, createMessageCliHelpers(message, "discord"));
193+
194+
await expect(
195+
program.parseAsync(
196+
[
197+
"message",
198+
"send",
199+
"--channel",
200+
"discord",
201+
"--target",
202+
"channel:123",
203+
"--message",
204+
"hi",
205+
...(dryRun ? ["--dry-run"] : []),
206+
],
207+
{ from: "user" },
208+
),
209+
).rejects.toThrow("exit");
210+
211+
expect(exitMock).toHaveBeenCalledWith(exitCode);
212+
},
213+
);
214+
153215
it("loads configured channel plugins when no target channel is known yet", async () => {
154216
await runSendAction({ channel: undefined });
155217

‎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 { isMessageBroadcastSuccessful } from "../../../infra/outbound/message-action-contracts.js";
18+
import { isMessageActionSuccessful } 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?.kind === "broadcast" && !isMessageBroadcastSuccessful(result);
224+
failed ||= result !== undefined && !isMessageActionSuccessful(result);
225225
defaultRuntime.exit(failed ? 1 : 0);
226226
};
227227

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,58 @@ describe("renderPaginationHint", () => {
215215
});
216216
});
217217

218+
describe("formatMessageCliText send results", () => {
219+
it.each([
220+
{
221+
status: "suppressed" as const,
222+
suppressionReason: "cancelled_by_message_sending_hook" as const,
223+
expected: "Message send suppressed: cancelled_by_message_sending_hook.",
224+
},
225+
{
226+
status: "failed" as const,
227+
error: "provider rejected the message",
228+
expected: "provider rejected the message",
229+
},
230+
{
231+
status: "partial_failed" as const,
232+
error: "second attachment rejected",
233+
messageId: "first-part-1",
234+
expected: "second attachment rejected",
235+
},
236+
])(
237+
"reports a $status delivery without claiming success",
238+
({ status, suppressionReason, error, messageId, expected }) => {
239+
const result = {
240+
kind: "send",
241+
action: "send",
242+
channel: "directchat",
243+
to: "room-1",
244+
handledBy: "core",
245+
payload: {},
246+
dryRun: false,
247+
sendResult: {
248+
channel: "directchat",
249+
to: "room-1",
250+
via: "direct",
251+
mediaUrl: null,
252+
deliveryStatus: status,
253+
...(suppressionReason ? { suppressionReason } : {}),
254+
...(error ? { error } : {}),
255+
...(messageId ? { result: { channel: "directchat", messageId } } : {}),
256+
},
257+
} satisfies MessageActionResult;
258+
259+
const output = textJoined(formatMessageCliText(result));
260+
261+
expect(output).toContain(expected);
262+
expect(output).not.toContain("✅ Sent");
263+
if (messageId) {
264+
expect(output).toContain(`Message ID: ${messageId}`);
265+
}
266+
},
267+
);
268+
});
269+
218270
describe("formatMessageCliText poll results", () => {
219271
it("formats direct core poll results as direct deliveries", () => {
220272
const result = {

‎src/commands/message-format.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ 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-
isMessageBroadcastSuccessful,
11+
isMessageActionSuccessful,
12+
resolveMessageSendOutcome,
1213
type MessageActionResult,
1314
} from "../infra/outbound/message-action-contracts.js";
1415
import { formatTargetDisplay } from "../infra/outbound/target-resolver.js";
@@ -299,7 +300,7 @@ export function formatMessageCliText(
299300
}));
300301
const okCount = results.filter((entry) => entry.ok).length;
301302
const total = results.length;
302-
const successful = isMessageBroadcastSuccessful(result);
303+
const successful = isMessageActionSuccessful(result);
303304
const headingLine = (successful ? ok : fail)(
304305
`${successful ? "✅ Broadcast complete" : "❌ Broadcast failed"} (${okCount}/${total} succeeded, ${total - okCount} failed)`,
305306
);
@@ -319,6 +320,11 @@ export function formatMessageCliText(
319320
}
320321

321322
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+
}
322328
if (result.handledBy === "core" && result.sendResult) {
323329
const send = result.sendResult;
324330
if (send.via === "direct") {

‎src/commands/message.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,8 +604,67 @@ describe("messageCommand", () => {
604604
channelId: "general",
605605
},
606606
});
607+
expect(json).not.toHaveProperty("ok");
607608
});
608609

610+
it.each([
611+
{
612+
status: "suppressed" as const,
613+
suppressionReason: "cancelled_by_message_sending_hook" as const,
614+
expected: "Message send suppressed: cancelled_by_message_sending_hook.",
615+
},
616+
{
617+
status: "failed" as const,
618+
error: "provider rejected the message",
619+
expected: "provider rejected the message",
620+
},
621+
{
622+
status: "partial_failed" as const,
623+
error: "second attachment rejected",
624+
messageId: "first-part-1",
625+
expected: "second attachment rejected",
626+
},
627+
])(
628+
"reports $status sends truthfully in JSON output",
629+
async ({ status, suppressionReason, error, messageId, expected }) => {
630+
const sendResult = {
631+
channel: "discord",
632+
to: "channel:general",
633+
via: "direct" as const,
634+
mediaUrl: null,
635+
deliveryStatus: status,
636+
...(suppressionReason ? { suppressionReason } : {}),
637+
...(error ? { error } : {}),
638+
...(messageId ? { result: { channel: "discord", messageId } } : {}),
639+
...(status === "partial_failed" ? { sentBeforeError: true as const } : {}),
640+
};
641+
runMessageActionMock.mockResolvedValueOnce({
642+
kind: "send",
643+
channel: "discord",
644+
action: "send",
645+
to: "channel:general",
646+
handledBy: "core",
647+
payload: sendResult,
648+
sendResult,
649+
dryRun: false,
650+
});
651+
652+
await runMessageCommand({ channel: "discord", target: "channel:general" });
653+
654+
const json = JSON.parse(String(vi.mocked(runtime.log).mock.calls[0]?.[0]));
655+
expect(json).toMatchObject({
656+
ok: false,
657+
deliveryStatus: status,
658+
error: { type: "cli_error", message: expected },
659+
});
660+
expect(json.payload).toEqual(sendResult);
661+
if (messageId) {
662+
expect(json.messageId).toBe(messageId);
663+
expect(json.sentBeforeError).toBe(true);
664+
}
665+
},
666+
);
667+
609668
it("rejects unknown message actions before dispatch", async () => {
610669
await expect(runMessageCommand({ action: "nope" })).rejects.toThrow("Unknown message action");
611670
expect(runMessageActionMock).not.toHaveBeenCalled();

‎src/commands/message.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type { ChannelMessageActionName } from "../channels/plugins/types.public.
1414
import { resolveCommandConfigWithSecrets } from "../cli/command-config-resolution.js";
1515
import { formatCliCommand } from "../cli/command-format.js";
1616
import { getScopedChannelsCommandSecretTargets } from "../cli/command-secret-targets.js";
17+
import { formatCliJsonFailure } from "../cli/failure-output.js";
1718
import { resolveMessageSecretScope } from "../cli/message-secret-scope.js";
1819
import { createOutboundSendDeps, type CliDeps } from "../cli/outbound-send-deps.js";
1920
import { withProgress } from "../cli/progress.js";
@@ -23,7 +24,10 @@ import {
2324
resolveMessageBroadcastAccountPlan,
2425
validateExplicitMessageAccountSelection,
2526
} from "../infra/outbound/message-account-selection.js";
26-
import { isMessageBroadcastSuccessful } from "../infra/outbound/message-action-contracts.js";
27+
import {
28+
isMessageActionSuccessful,
29+
resolveMessageSendOutcome,
30+
} from "../infra/outbound/message-action-contracts.js";
2731
import { runMessageAction } from "../infra/outbound/message-action-runner.js";
2832
import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
2933

@@ -48,8 +52,18 @@ function extractMessageId(payload: unknown): string | undefined {
4852

4953
function buildMessageCliJson(result: Awaited<ReturnType<typeof runMessageAction>>) {
5054
const messageId = extractMessageId(result.payload);
55+
const sendResult = result.kind === "send" ? result.sendResult : undefined;
56+
const sendOutcome = result.kind === "send" ? resolveMessageSendOutcome(sendResult) : undefined;
5157
return {
52-
...(result.kind === "broadcast" ? { ok: isMessageBroadcastSuccessful(result) } : {}),
58+
...(result.kind === "broadcast"
59+
? { ok: isMessageActionSuccessful(result) }
60+
: sendOutcome && !sendOutcome.ok && !result.dryRun
61+
? {
62+
...formatCliJsonFailure(sendOutcome.error),
63+
deliveryStatus: sendResult?.deliveryStatus,
64+
...(sendOutcome.sentBeforeError ? { sentBeforeError: true } : {}),
65+
}
66+
: {}),
5367
action: result.action,
5468
channel: result.channel,
5569
dryRun: result.dryRun,

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

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,39 @@ export type MessageActionResult =
178178
dryRun: boolean;
179179
};
180180

181-
export const isMessageBroadcastSuccessful = (
182-
result: Extract<MessageActionResult, { kind: "broadcast" }>,
183-
): boolean => result.payload.results.every((entry) => entry.ok);
181+
export function resolveMessageSendOutcome(
182+
sendResult: MessageSendResult | undefined,
183+
action: "Message" | "Broadcast" = "Message",
184+
): { ok: true } | { ok: false; error: string; sentBeforeError?: true } {
185+
if (
186+
!sendResult ||
187+
sendResult.deliveryStatus === undefined ||
188+
sendResult.deliveryStatus === "sent"
189+
) {
190+
return { ok: true };
191+
}
192+
switch (sendResult.deliveryStatus) {
193+
case "suppressed":
194+
return {
195+
ok: false,
196+
error: `${action} send suppressed: ${sendResult.suppressionReason ?? "unknown reason"}.`,
197+
};
198+
case "failed":
199+
return { ok: false, error: sendResult.error ?? `${action} send failed.` };
200+
case "partial_failed":
201+
return {
202+
ok: false,
203+
error: sendResult.error ?? `${action} send partially failed.`,
204+
sentBeforeError: true,
205+
};
206+
}
207+
return sendResult.deliveryStatus satisfies never;
208+
}
209+
210+
export const isMessageActionSuccessful = (result: MessageActionResult): boolean =>
211+
result.kind === "broadcast"
212+
? result.payload.results.every((entry) => entry.ok)
213+
: result.kind !== "send" || result.dryRun || resolveMessageSendOutcome(result.sendResult).ok;
184214

185215
export type ResolvedActionContext = {
186216
cfg: OpenClawConfig;

0 commit comments

Comments
 (0)