Skip to content

Commit 91cc7d5

Browse files
authored
fix(cli): report broadcast delivery failures (#125915)
* fix(cli): report broadcast delivery failures * test(qa): wait for descendant process exit
1 parent b1d53fc commit 91cc7d5

8 files changed

Lines changed: 211 additions & 19 deletions

File tree

‎src/cli/help-exit.process.test.ts‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Process coverage for CLI help exits and route-first fallback validation.
2-
import { spawn } from "node:child_process";
2+
import { spawn, spawnSync } from "node:child_process";
33
import { once } from "node:events";
44
import fs from "node:fs/promises";
55
import path from "node:path";
@@ -398,6 +398,70 @@ describe("rejected CLI process state isolation", () => {
398398
});
399399
});
400400

401+
describe("message broadcast process exit", () => {
402+
it("exits nonzero after a structured target failure", async () => {
403+
const root = tempDirs.make("openclaw-message-broadcast-exit-");
404+
const stateDir = path.join(root, "state");
405+
const configPath = path.join(stateDir, "openclaw.json");
406+
const entryPath = path.join(root, "run-message-broadcast.mjs");
407+
await fs.writeFile(
408+
entryPath,
409+
`import { registerHooks } from "node:module";
410+
const messageModule = "data:text/javascript," + encodeURIComponent(\`export async function messageCommand() {
411+
return ${JSON.stringify({
412+
kind: "broadcast",
413+
channel: "fixture",
414+
action: "broadcast",
415+
handledBy: "core",
416+
payload: {
417+
results: [
418+
{ channel: "fixture", to: "ok-target", ok: true },
419+
{ channel: "fixture", to: "failed-target", ok: false, error: "delivery failed" },
420+
],
421+
},
422+
dryRun: false,
423+
})};
424+
}\`);
425+
registerHooks({
426+
resolve(specifier, context, nextResolve) {
427+
return specifier === "../../../commands/message.js"
428+
? { shortCircuit: true, url: messageModule }
429+
: nextResolve(specifier, context);
430+
},
431+
});
432+
const { createMessageCliHelpers } = await import(${JSON.stringify(pathToFileURL(path.resolve("src/cli/program/message/helpers.ts")).href)});
433+
const { runMessageAction } = createMessageCliHelpers({}, "fixture");
434+
await runMessageAction("broadcast", {
435+
channel: "fixture",
436+
targets: ["ok-target", "failed-target"],
437+
message: "hello",
438+
});
439+
`,
440+
);
441+
442+
const child = spawnSync(process.execPath, ["--import", "tsx", entryPath], {
443+
cwd: path.resolve("."),
444+
encoding: "utf8",
445+
env: {
446+
...process.env,
447+
HOME: root,
448+
NODE_ENV: undefined,
449+
NODE_OPTIONS: undefined,
450+
OPENCLAW_CONFIG_PATH: configPath,
451+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
452+
OPENCLAW_NO_RESPAWN: "1",
453+
OPENCLAW_STATE_DIR: stateDir,
454+
VITEST: undefined,
455+
},
456+
timeout: DEFAULT_CHILD_PROCESS_TIMEOUT_MS,
457+
});
458+
459+
expect(child.error).toBeUndefined();
460+
expect(child.signal).toBeNull();
461+
expect(child.status, child.stderr).toBe(1);
462+
});
463+
});
464+
401465
describe("JSON console style process output", () => {
402466
const loggingConfig = {
403467
logging: {

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

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
33
import { beforeEach, describe, expect, it, vi } from "vitest";
44

5-
const messageCommandMock = vi.fn(async () => {});
5+
const messageCommandMock = vi.fn(async (): Promise<unknown> => undefined);
66
vi.mock("../../../commands/message.js", () => ({
77
messageCommand: messageCommandMock,
88
}));
@@ -52,7 +52,7 @@ vi.mock("../../../plugins/hook-runner-global.js", () => ({
5252
runGlobalGatewayStopSafely: runGlobalGatewayStopSafelyMock,
5353
}));
5454

55-
const exitMock = vi.fn((): never => {
55+
const exitMock = vi.fn((_code: number): never => {
5656
throw new Error("exit");
5757
});
5858
const errorMock = vi.fn();
@@ -137,7 +137,7 @@ describe("runMessageAction", () => {
137137
hasHooksMock.mockClear().mockReturnValue(false);
138138
runGatewayStopMock.mockClear().mockResolvedValue(undefined);
139139
runGlobalGatewayStopSafelyMock.mockClear();
140-
exitMock.mockClear().mockImplementation((): never => {
140+
exitMock.mockClear().mockImplementation((_code: number): never => {
141141
throw new Error("exit");
142142
});
143143
});
@@ -510,6 +510,43 @@ describe("runMessageAction", () => {
510510
expect(exitMock).toHaveBeenCalledWith(1);
511511
});
512512

513+
it("runs gateway_stop hooks before exit(1) for a failed broadcast result", async () => {
514+
const order: string[] = [];
515+
hasHooksMock.mockReturnValueOnce(true);
516+
messageCommandMock.mockResolvedValueOnce({
517+
kind: "broadcast",
518+
channel: "telegram",
519+
action: "broadcast",
520+
handledBy: "core",
521+
payload: {
522+
results: [
523+
{ channel: "telegram", to: "123", ok: true },
524+
{ channel: "telegram", to: "456", ok: false, error: "delivery failed" },
525+
],
526+
},
527+
dryRun: false,
528+
});
529+
runGatewayStopMock.mockImplementationOnce(async () => {
530+
order.push("stop");
531+
});
532+
exitMock.mockImplementationOnce((code: number): never => {
533+
order.push(`exit:${code}`);
534+
throw new Error("exit");
535+
});
536+
const runMessageAction = createRunMessageAction();
537+
538+
await expect(
539+
runMessageAction("broadcast", {
540+
channel: "telegram",
541+
targets: ["123", "456"],
542+
message: "hi",
543+
}),
544+
).rejects.toThrow("exit");
545+
546+
expect(order).toEqual(["stop", "exit:1"]);
547+
expect(exitMock).not.toHaveBeenCalledWith(0);
548+
});
549+
513550
it("logs gateway_stop failure and still exits with success code", async () => {
514551
hasHooksMock.mockReturnValueOnce(true);
515552
runGatewayStopMock.mockRejectedValueOnce(new Error("hook failed"));

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +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";
1819
import { withActivatedPluginIds } from "../../../plugins/activation-context.js";
1920
import {
2021
resolveConfiguredChannelPluginIds,
@@ -167,6 +168,7 @@ export function createMessageCliHelpers(
167168
const runMessageAction = async (action: string, opts: Record<string, unknown>) => {
168169
setVerbose(Boolean(opts.verbose));
169170
let failed = false;
171+
let result: Awaited<ReturnType<typeof messageCommand>> | undefined;
170172
let pluginRegistry: PluginRegistry | undefined;
171173
await runCommandWithRuntime(
172174
defaultRuntime,
@@ -208,7 +210,7 @@ export function createMessageCliHelpers(
208210
deps,
209211
defaultRuntime,
210212
);
211-
await withPluginRuntimeRegistryScope(pluginRegistry, run);
213+
result = await withPluginRuntimeRegistryScope(pluginRegistry, run);
212214
},
213215
(err) => {
214216
failed = true;
@@ -219,6 +221,7 @@ export function createMessageCliHelpers(
219221
if (!ACTIONS_WITHOUT_STOP_HOOKS.has(action)) {
220222
await withPluginRuntimeRegistryScope(pluginRegistry, runPluginStopHooks);
221223
}
224+
failed ||= result?.kind === "broadcast" && !isMessageBroadcastSuccessful(result);
222225
defaultRuntime.exit(failed ? 1 : 0);
223226
};
224227

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

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,3 +248,47 @@ describe("formatMessageCliText poll results", () => {
248248
]);
249249
});
250250
});
251+
252+
describe("formatMessageCliText broadcast results", () => {
253+
it("reports aggregate failure while preserving every target row", () => {
254+
const result = {
255+
kind: "broadcast",
256+
action: "broadcast",
257+
channel: "directchat",
258+
handledBy: "core",
259+
payload: {
260+
results: [
261+
...Array.from({ length: 51 }, (_, index) => ({
262+
channel: "directchat" as const,
263+
to: `room-ok-${index}`,
264+
ok: true as const,
265+
})),
266+
{
267+
channel: "directchat",
268+
to: "room-suppressed",
269+
ok: false,
270+
error: "Broadcast send suppressed: cancelled_by_message_sending_hook.",
271+
},
272+
{
273+
channel: "directchat",
274+
to: "room-partial",
275+
ok: false,
276+
error: "second payload failed",
277+
sentBeforeError: true,
278+
},
279+
],
280+
},
281+
dryRun: false,
282+
} satisfies MessageActionResult;
283+
284+
const output = textJoined(formatMessageCliText(result));
285+
286+
expect(output).toContain("Broadcast failed (51/53 succeeded, 2 failed)");
287+
expect(output).not.toContain("Broadcast complete");
288+
expect(output).toContain("room-ok-50");
289+
expect(output).toContain("room-suppressed");
290+
expect(output).toContain("room-partial");
291+
expect(output).toContain("Broadcast send suppressed");
292+
expect(output).toContain("second payload failed");
293+
});
294+
});

‎src/commands/message-format.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ import { getLoadedChannelPlugin } from "../channels/plugins/index.js";
77
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";
10-
import type { MessageActionResult } from "../infra/outbound/message-action-contracts.js";
10+
import {
11+
isMessageBroadcastSuccessful,
12+
type MessageActionResult,
13+
} from "../infra/outbound/message-action-contracts.js";
1114
import { formatTargetDisplay } from "../infra/outbound/target-resolver.js";
1215
import { shortenText } from "./text-format.js";
1316

@@ -274,6 +277,7 @@ export function formatMessageCliText(
274277
): string[] {
275278
const rich = isRich();
276279
const ok = (text: string) => (rich ? theme.success(text) : text);
280+
const fail = (text: string) => (rich ? theme.error(text) : text);
277281
const muted = (text: string) => (rich ? theme.muted(text) : text);
278282
const heading = (text: string) => (rich ? theme.heading(text) : text);
279283

@@ -295,8 +299,9 @@ export function formatMessageCliText(
295299
}));
296300
const okCount = results.filter((entry) => entry.ok).length;
297301
const total = results.length;
298-
const headingLine = ok(
299-
`✅ Broadcast complete (${okCount}/${total} succeeded, ${total - okCount} failed)`,
302+
const successful = isMessageBroadcastSuccessful(result);
303+
const headingLine = (successful ? ok : fail)(
304+
`${successful ? "✅ Broadcast complete" : "❌ Broadcast failed"} (${okCount}/${total} succeeded, ${total - okCount} failed)`,
300305
);
301306
return [
302307
headingLine,
@@ -308,7 +313,7 @@ export function formatMessageCliText(
308313
{ key: "Status", header: "Status", minWidth: 6 },
309314
{ key: "Error", header: "Error", minWidth: 20, flex: true },
310315
],
311-
rows: rows.slice(0, 50),
316+
rows,
312317
}).trimEnd(),
313318
];
314319
}

‎src/commands/message.test.ts‎

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite
33
import type { ChannelPlugin } from "../channels/plugins/types.js";
44
import type { CliDeps } from "../cli/deps.js";
55
import { migratePersistedImplicitMainRoster } from "../config/legacy.roster.js";
6+
import type { MessageActionResult } from "../infra/outbound/message-action-contracts.js";
67
import type { RuntimeEnv } from "../runtime.js";
78
import { captureEnv } from "../test-utils/env.js";
89

@@ -97,15 +98,18 @@ vi.mock("../cli/command-secret-targets.js", () => ({
9798
}));
9899

99100
const runMessageActionMock = vi.hoisted(() =>
100-
vi.fn(async ({ action, params }: RunMessageActionParams) => ({
101-
kind: action === "poll" ? "poll" : "send",
102-
channel: typeof params.channel === "string" ? params.channel : "telegram",
103-
action: action === "poll" ? "poll" : "send",
104-
to: typeof params.target === "string" ? params.target : "123456",
105-
handledBy: "plugin",
106-
payload: { ok: true },
107-
dryRun: false,
108-
})),
101+
vi.fn(async ({ action, params }: RunMessageActionParams): Promise<MessageActionResult> => {
102+
const base = {
103+
channel: typeof params.channel === "string" ? params.channel : "telegram",
104+
to: typeof params.target === "string" ? params.target : "123456",
105+
handledBy: "plugin" as const,
106+
payload: { ok: true },
107+
dryRun: false,
108+
};
109+
return action === "poll"
110+
? { ...base, kind: "poll", action: "poll" }
111+
: { ...base, kind: "send", action: "send" };
112+
}),
109113
);
110114

111115
vi.mock("../infra/outbound/message-action-runner.js", () => ({
@@ -253,6 +257,34 @@ async function runMessageCommand(opts: Record<string, unknown> = {}) {
253257
}
254258

255259
describe("messageCommand", () => {
260+
it("includes aggregate broadcast failure and every target row in JSON output", async () => {
261+
const results: Extract<MessageActionResult, { kind: "broadcast" }>["payload"]["results"] = [
262+
{ channel: "telegram", to: "123", ok: true },
263+
{ channel: "telegram", to: "456", ok: false, error: "provider rejected the message" },
264+
];
265+
runMessageActionMock.mockResolvedValueOnce({
266+
kind: "broadcast",
267+
channel: "telegram",
268+
action: "broadcast",
269+
handledBy: "core",
270+
payload: { results },
271+
dryRun: false,
272+
});
273+
274+
await runMessageCommand({
275+
action: "broadcast",
276+
target: undefined,
277+
targets: ["123", "456"],
278+
});
279+
280+
const output = JSON.parse(String(vi.mocked(runtime.log).mock.calls[0]?.[0])) as {
281+
ok?: boolean;
282+
payload?: { results?: unknown[] };
283+
};
284+
expect(output.ok).toBe(false);
285+
expect(output.payload?.results).toEqual(results);
286+
});
287+
256288
it("rejects a malformed explicit account before resolving secrets", async () => {
257289
await expect(runMessageCommand({ accountId: "!!!" })).rejects.toThrow("Invalid account ID");
258290

‎src/commands/message.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
resolveMessageBroadcastAccountPlan,
2525
validateExplicitMessageAccountSelection,
2626
} from "../infra/outbound/message-account-selection.js";
27+
import { isMessageBroadcastSuccessful } from "../infra/outbound/message-action-contracts.js";
2728
import { runMessageAction } from "../infra/outbound/message-action-runner.js";
2829
import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
2930

@@ -49,6 +50,7 @@ function extractMessageId(payload: unknown): string | undefined {
4950
function buildMessageCliJson(result: Awaited<ReturnType<typeof runMessageAction>>) {
5051
const messageId = extractMessageId(result.payload);
5152
return {
53+
...(result.kind === "broadcast" ? { ok: isMessageBroadcastSuccessful(result) } : {}),
5254
action: result.action,
5355
channel: result.channel,
5456
dryRun: result.dryRun,
@@ -158,12 +160,13 @@ export async function messageCommand(
158160

159161
if (json) {
160162
writeRuntimeJson(runtime, buildMessageCliJson(result));
161-
return;
163+
return result;
162164
}
163165

164166
const { formatMessageCliText } = await import("./message-format.js");
165167
const displayLimit = parseStrictPositiveInteger(opts.limit);
166168
for (const line of formatMessageCliText(result, { displayLimit })) {
167169
runtime.log(line);
168170
}
171+
return result;
169172
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,10 @@ export type MessageActionResult =
169169
dryRun: boolean;
170170
};
171171

172+
export const isMessageBroadcastSuccessful = (
173+
result: Extract<MessageActionResult, { kind: "broadcast" }>,
174+
): boolean => result.payload.results.every((entry) => entry.ok);
175+
172176
export type ResolvedActionContext = {
173177
cfg: OpenClawConfig;
174178
params: Record<string, unknown>;

0 commit comments

Comments
 (0)