File size: 26,111 Bytes
eb3f11e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
// Message program helper tests cover message command helper behavior and mocks.
import { Command } from "commander";
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { addTestHook, createMockPluginRegistry } from "../../../plugins/hooks.test-helpers.js";
import { registerMessagePollCommand } from "./register.poll.js";
import { registerMessageReactionsCommands } from "./register.reactions.js";
import { registerMessageReadEditDeleteCommands } from "./register.read-edit-delete.js";
import { registerMessageSendCommand } from "./register.send.js";

const messageCommandMock = vi.fn(async (): Promise<unknown> => undefined);
vi.mock("../../../commands/message.js", () => ({
  messageCommand: messageCommandMock,
}));

const getChannelPluginMock = vi.fn();
vi.mock("../../../channels/plugins/index.js", () => ({
  getChannelPlugin: getChannelPluginMock,
}));

vi.mock("../../../globals.js", () => ({
  danger: (s: string) => s,
  setVerbose: vi.fn(),
}));

const pluginRegistry = createMockPluginRegistry([]);
const loadPluginRegistryHandleMock = vi.fn(() => pluginRegistry);
vi.mock("../../../config/config.js", () => ({ getRuntimeConfig: () => ({}) }));
vi.mock("../../../plugins/channel-plugin-ids.js", () => ({
  resolveConfiguredChannelPluginIds: () => ["configured-channel"],
  resolveDiscoverableScopedChannelPluginIds: (params: { channelIds: string[] }) =>
    params.channelIds,
}));
vi.mock("../../../plugins/loader.js", () => ({
  loadPluginRegistryHandle: loadPluginRegistryHandleMock,
}));

const runGatewayStopMock = vi.fn(
  async (_eventValue: { reason?: string }, _ctx: Record<string, unknown>) => {},
);
const hookErrorMock = vi.fn();
vi.mock("../../../logging/subsystem.js", () => ({
  createSubsystemLogger: () => ({
    debug: vi.fn(),
    warn: hookErrorMock,
    error: hookErrorMock,
  }),
}));

function registerStopHook() {
  addTestHook({
    registry: pluginRegistry,
    pluginId: "test-plugin",
    hookName: "gateway_stop",
    handler: runGatewayStopMock,
  });
}

const exitMock = vi.fn((_code: number): never => {
  throw new Error("exit");
});
const errorMock = vi.fn();
const runtimeMock = { log: vi.fn(), error: errorMock, exit: exitMock };
vi.mock("../../../runtime.js", async (importOriginal) => ({
  ...(await importOriginal<typeof import("../../../runtime.js")>()),
  defaultRuntime: runtimeMock,
}));

// Forward to the same synchronous-throwing exit mock: runMessageAction only defers the
// real exit via the one-shot output drain, which these tests don't exercise directly.
vi.mock("../../one-shot-exit.js", () => ({
  requestExitAfterOneShotOutput: (runtime: { exit: (code: number) => never }, exitCode = 0) => {
    runtime.exit(exitCode);
    return true;
  },
}));

vi.mock("../../deps.js", () => ({
  createDefaultDeps: () => ({}),
}));

const { createMessageCliHelpers } = await import("./helpers.js");
const { initializeGlobalHookRunner, resetGlobalHookRunner } =
  await import("../../../plugins/hook-runner-global.js");
afterEach(resetGlobalHookRunner);

const NON_NEGATIVE_INTEGER_FLAGS = new Set(["--delete-days", "--duration-min"]);

const baseSendOptions = {
  channel: "discord",
  target: "123",
  message: "hi",
};

function createRunMessageAction() {
  return createMessageCliHelpers("discord").runMessageAction;
}

async function runSendAction(opts: Record<string, unknown> = {}) {
  const runMessageAction = createRunMessageAction();
  await expect(runMessageAction("send", { ...baseSendOptions, ...opts })).rejects.toThrow("exit");
}

function mockChannelExecutionModes(modes: Record<string, "gateway" | "local"> = {}) {
  getChannelPluginMock.mockImplementation((id: string) => ({
    actions: {
      resolveExecutionMode: () => modes[id] ?? "local",
    },
  }));
}

function expectNoAccountFieldInPassedOptions() {
  const passedOpts = (
    messageCommandMock.mock.calls as unknown as Array<[Record<string, unknown>]>
  )?.[0]?.[0];
  if (passedOpts === undefined) {
    throw new Error("expected message command call");
  }
  expect(passedOpts).not.toHaveProperty("account");
}

const requireRecord = createRequireRecord("record", "expected-label-object");

function expectMessageCommandOptions(expected: Record<string, unknown>, callIndex = 0): void {
  const call = (messageCommandMock.mock.calls as unknown[][])[callIndex];
  if (!call) {
    throw new Error(`expected messageCommand call ${callIndex}`);
  }
  const options = requireRecord(call[0], `messageCommand options ${callIndex}`);
  for (const [key, expectedValue] of Object.entries(expected)) {
    expect(options[key], `messageCommand options.${key}`).toEqual(expectedValue);
  }
  if (call[1] == null) {
    throw new Error("expected messageCommand runtime");
  }
  if (call[2] == null) {
    throw new Error("expected messageCommand deps");
  }
}

function expectRegistryLoad(pluginIds: string[]): void {
  expect(loadPluginRegistryHandleMock).toHaveBeenCalledWith(
    expect.objectContaining({ onlyPluginIds: pluginIds, throwOnLoadError: true }),
  );
}

describe("runMessageAction", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    getChannelPluginMock.mockReset();
    mockChannelExecutionModes({ telegram: "gateway" });
    messageCommandMock.mockClear().mockResolvedValue(undefined);
    pluginRegistry.typedHooks.length = 0;
    resetGlobalHookRunner();
    runGatewayStopMock.mockClear().mockResolvedValue(undefined);
    exitMock.mockClear().mockImplementation((_code: number): never => {
      throw new Error("exit");
    });
  });

  it("calls exit(0) after successful message delivery", async () => {
    await runSendAction();

    expectRegistryLoad(["discord"]);
    expect(exitMock).toHaveBeenCalledOnce();
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it.each([
    { name: "sent", status: "sent" as const, exitCode: 0 },
    { name: "suppressed", status: "suppressed" as const, exitCode: 1 },
    { name: "failed", status: "failed" as const, exitCode: 1 },
    { name: "partial_failed", status: "partial_failed" as const, exitCode: 1 },
    { name: "dry-run", status: undefined, dryRun: true, exitCode: 0 },
  ])(
    "propagates $name send outcomes through the real CLI parser",
    async ({ status, dryRun, exitCode }) => {
      const sendResult = {
        channel: "discord",
        to: "channel:123",
        via: "direct" as const,
        mediaUrl: null,
        ...(status ? { deliveryStatus: status } : {}),
        ...(status === "suppressed"
          ? { suppressionReason: "cancelled_by_message_sending_hook" as const }
          : {}),
        ...(status === "failed" || status === "partial_failed"
          ? { error: "provider rejected the message" }
          : {}),
        ...(status === "partial_failed"
          ? { sentBeforeError: true as const, result: { channel: "discord", messageId: "part-1" } }
          : {}),
      };
      messageCommandMock.mockResolvedValueOnce({
        kind: "send",
        channel: "discord",
        action: "send",
        to: "channel:123",
        handledBy: "core",
        payload: sendResult,
        sendResult,
        dryRun: Boolean(dryRun),
      });
      const program = new Command();
      const message = program.command("message");
      registerMessageSendCommand(message, createMessageCliHelpers("discord"));

      await expect(
        program.parseAsync(
          [
            "message",
            "send",
            "--channel",
            "discord",
            "--target",
            "channel:123",
            "--message",
            "hi",
            ...(dryRun ? ["--dry-run"] : []),
          ],
          { from: "user" },
        ),
      ).rejects.toThrow("exit");

      expect(exitMock).toHaveBeenCalledWith(exitCode);
    },
  );

  it.each(["", "   "])(
    "rejects an explicitly blank message channel before command startup (%j)",
    async (channel) => {
      const program = new Command().exitOverride().configureOutput({ writeErr: () => undefined });
      const message = program.command("message");
      registerMessageSendCommand(message, createMessageCliHelpers("discord"));

      await expect(
        program.parseAsync(
          ["message", "send", "--channel", channel, "--target", "channel:123", "--message", "hi"],
          { from: "user" },
        ),
      ).rejects.toThrow("--channel must not be blank");

      expect(loadPluginRegistryHandleMock).not.toHaveBeenCalled();
      expect(messageCommandMock).not.toHaveBeenCalled();
    },
  );

  it.each([
    ["disabled reaction", "react", { ok: false, hint: "Reactions are disabled." }, 1],
    ["rejected added reaction", "react", { ok: false, warning: "Unavailable", added: "✅" }, 1],
    ["rejected delete", "delete", { ok: false, deleted: false, warning: "Not deleted" }, 1],
    ["rejected poll", "poll", { ok: false, error: "Poll rejected" }, 1],
    ["rejected send", "send", { ok: false, error: "Message rejected" }, 1],
    ["successful reaction", "react", { ok: true, added: "✅" }, 0],
    ["legacy reaction", "react", { added: "✅" }, 0],
    ["non-boolean outcome", "react", { ok: "false", added: "✅" }, 0],
    ["dry-run", "react", { ok: false, error: "Not executed" }, 0],
  ] as const)(
    "propagates %s through the real CLI parser",
    async (name, action, payload, exitCode) => {
      const dryRun = name === "dry-run";
      const kind = action === "send" || action === "poll" ? action : "action";
      messageCommandMock.mockResolvedValueOnce({
        kind,
        channel: "telegram",
        action,
        ...(kind === "action" ? {} : { to: "123" }),
        handledBy: "plugin",
        payload,
        dryRun,
      });
      const program = new Command();
      const message = program.command("message");
      const helpers = createMessageCliHelpers("telegram");
      registerMessageSendCommand(message, helpers);
      registerMessagePollCommand(message, helpers);
      registerMessageReactionsCommands(message, helpers);
      registerMessageReadEditDeleteCommands(message, helpers);
      const args = {
        react: ["--message-id", "456", "--emoji", "✅"],
        delete: ["--message-id", "456"],
        poll: ["--poll-question", "Ready?", "--poll-option", "Yes", "--poll-option", "No"],
        send: ["--message", "hello"],
      }[action];

      await expect(
        program.parseAsync(
          [
            "message",
            action,
            "--channel",
            "telegram",
            "--target",
            "123",
            ...args,
            ...(dryRun ? ["--dry-run"] : []),
          ],
          { from: "user" },
        ),
      ).rejects.toThrow("exit");

      expect(exitMock).toHaveBeenCalledWith(exitCode);
    },
  );

  it("loads configured channel plugins when no target channel is known yet", async () => {
    await runSendAction({ channel: undefined });

    expectRegistryLoad(["configured-channel"]);
  });

  it("narrows plugin loading from a channel-prefixed target", async () => {
    await runSendAction({ channel: undefined, target: "discord:channel:12345" });

    expectRegistryLoad(["discord"]);
  });

  it("skips local plugin preload for any gateway-owned scoped channel action", async () => {
    mockChannelExecutionModes({ discord: "gateway" });

    await runSendAction({ target: "channel:12345" });

    expect(loadPluginRegistryHandleMock).not.toHaveBeenCalled();
    expectMessageCommandOptions({
      action: "send",
      channel: "discord",
      target: "channel:12345",
      message: "hi",
    });
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it("keeps broadcast on the local preload path for same-channel prefixed targets", async () => {
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("broadcast", {
        targets: ["telegram:1", "telegram:2"],
        message: "hi",
      }),
    ).rejects.toThrow("exit");

    expectRegistryLoad(["telegram"]);
    expectMessageCommandOptions({
      action: "broadcast",
      targets: ["telegram:1", "telegram:2"],
      message: "hi",
    });
  });

  it("keeps unknown actions on the local preload path", async () => {
    mockChannelExecutionModes({ discord: "gateway" });
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("custom-action", {
        ...baseSendOptions,
        target: "channel:12345",
      }),
    ).rejects.toThrow("exit");

    expectRegistryLoad(["discord"]);
    expectMessageCommandOptions({ action: "custom-action" });
  });

  it("preloads when the scoped channel plugin is not cheaply available", async () => {
    getChannelPluginMock.mockReturnValue(undefined);

    await runSendAction({ target: "channel:12345" });

    expectRegistryLoad(["discord"]);
  });

  it("keeps target-prefixed Telegram sends from local plugin preload", async () => {
    await runSendAction({ channel: undefined, target: "telegram:12345" });

    expect(loadPluginRegistryHandleMock).not.toHaveBeenCalled();
    expectMessageCommandOptions({
      action: "send",
      target: "telegram:12345",
      message: "hi",
    });
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it("keeps explicit Telegram sends on the normal command path without local plugin preload", async () => {
    await runSendAction({
      channel: "telegram",
      account: "default",
      target: "@ops",
      media: "./diagram.png",
      presentation: '{"blocks":[{"type":"buttons","buttons":[{"label":"OK","value":"ok"}]}]}',
      delivery: '{"pin":true}',
      forceDocument: true,
    });

    expect(loadPluginRegistryHandleMock).not.toHaveBeenCalled();
    expectMessageCommandOptions({
      action: "send",
      channel: "telegram",
      accountId: "default",
      target: "@ops",
      message: "hi",
      media: "./diagram.png",
      presentation: '{"blocks":[{"type":"buttons","buttons":[{"label":"OK","value":"ok"}]}]}',
      delivery: '{"pin":true}',
      forceDocument: true,
    });
    expectNoAccountFieldInPassedOptions();
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it("keeps Telegram dry-runs on the local preload path for local validation", async () => {
    await runSendAction({
      channel: "telegram",
      target: "@ops",
      dryRun: true,
    });

    expectRegistryLoad(["telegram"]);
    expect(messageCommandMock).toHaveBeenCalledTimes(1);
  });

  it("loads configured channel plugins for mixed broadcast target prefixes", async () => {
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("broadcast", {
        targets: ["discord:channel:1", "telegram:123"],
        message: "hi",
      }),
    ).rejects.toThrow("exit");

    expectRegistryLoad(["configured-channel"]);
  });

  it("exits with failure when plugin registry loading fails before dispatch", async () => {
    loadPluginRegistryHandleMock.mockImplementationOnce(() => {
      throw new Error("plugin load failed");
    });

    await runSendAction();

    expect(messageCommandMock).not.toHaveBeenCalled();
    expect(errorMock).toHaveBeenCalledWith("plugin load failed");
    expect(exitMock).toHaveBeenCalledOnce();
    expect(exitMock).toHaveBeenCalledWith(1);
    expect(exitMock).not.toHaveBeenCalledWith(0);
  });

  it("rejects conflicting poll visibility flags before loading channel plugins", async () => {
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("poll", {
        channel: "telegram",
        target: "123",
        pollQuestion: "Ship it?",
        pollOption: ["Yes", "No"],
        pollAnonymous: true,
        pollPublic: true,
      }),
    ).rejects.toThrow("exit");

    expect(errorMock).toHaveBeenCalledWith(
      "--poll-anonymous and --poll-public are mutually exclusive.",
    );
    expect(loadPluginRegistryHandleMock).not.toHaveBeenCalled();
    expect(messageCommandMock).not.toHaveBeenCalled();
    expect(exitMock).toHaveBeenCalledWith(1);
    expect(exitMock).not.toHaveBeenCalledWith(0);
  });

  it.each([
    [
      "poll duration hours",
      "poll",
      {
        channel: "discord",
        target: "123",
        pollQuestion: "ship?",
        pollOption: ["yes", "no"],
        pollDurationHours: "1.5",
      },
      "--poll-duration-hours",
    ],
    [
      "poll duration seconds",
      "poll",
      {
        channel: "telegram",
        target: "123",
        pollQuestion: "ship?",
        pollOption: ["yes", "no"],
        pollDurationSeconds: "60s",
      },
      "--poll-duration-seconds",
    ],
    [
      "timeout duration",
      "timeout",
      { guildId: "g", userId: "u", durationMin: "5m" },
      "--duration-min",
    ],
    ["ban delete days", "ban", { guildId: "g", userId: "u", deleteDays: "7d" }, "--delete-days"],
    ["read limit", "read", { channel: "discord", target: "123", limit: "10x" }, "--limit"],
    ["search limit", "search", { guildId: "g", query: "hello", limit: "10x" }, "--limit"],
    ["pins limit", "list-pins", { channel: "discord", target: "123", limit: "10x" }, "--limit"],
    [
      "reactions limit",
      "reactions",
      { channel: "discord", target: "123", messageId: "m", limit: "10x" },
      "--limit",
    ],
    [
      "thread auto archive minutes",
      "thread-create",
      {
        channel: "discord",
        target: "123",
        threadName: "ops",
        autoArchiveMin: "60m",
      },
      "--auto-archive-min",
    ],
    ["thread list limit", "thread-list", { guildId: "g", limit: "10x" }, "--limit"],
  ])("rejects malformed numeric CLI option for %s", async (_name, action, opts, flag) => {
    const runMessageAction = createRunMessageAction();

    await expect(runMessageAction(action, opts)).rejects.toThrow("exit");

    const kind = NON_NEGATIVE_INTEGER_FLAGS.has(flag) ? "non-negative" : "positive";
    expect(errorMock).toHaveBeenCalledWith(`${flag} must be a ${kind} integer.`);
    expect(loadPluginRegistryHandleMock).not.toHaveBeenCalled();
    expect(messageCommandMock).not.toHaveBeenCalled();
    expect(exitMock).toHaveBeenCalledWith(1);
    expect(exitMock).not.toHaveBeenCalledWith(0);
  });

  it.each([
    ["pollDurationHours", "0", "--poll-duration-hours"],
    ["pollDurationSeconds", "-1", "--poll-duration-seconds"],
    ["durationMin", "", "--duration-min"],
    ["deleteDays", Number.NaN, "--delete-days"],
    ["limit", 1.2, "--limit"],
    ["autoArchiveMin", null, "--auto-archive-min"],
  ])("rejects non-positive or non-integer %s values", async (key, value, flag) => {
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("send", {
        ...baseSendOptions,
        [key]: value,
      }),
    ).rejects.toThrow("exit");

    const kind = NON_NEGATIVE_INTEGER_FLAGS.has(flag) ? "non-negative" : "positive";
    expect(errorMock).toHaveBeenCalledWith(`${flag} must be a ${kind} integer.`);
    expect(messageCommandMock).not.toHaveBeenCalled();
    expect(exitMock).toHaveBeenCalledWith(1);
  });

  it("allows zero delete-days for no-history Discord bans", async () => {
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("ban", {
        guildId: "g",
        userId: "u",
        deleteDays: "0",
      }),
    ).rejects.toThrow("exit");

    expect(errorMock).not.toHaveBeenCalled();
    expectMessageCommandOptions({
      action: "ban",
      guildId: "g",
      userId: "u",
      deleteDays: "0",
    });
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it("allows zero duration-min for clearing Discord timeouts", async () => {
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("timeout", {
        guildId: "g",
        userId: "u",
        durationMin: "0",
      }),
    ).rejects.toThrow("exit");

    expect(errorMock).not.toHaveBeenCalled();
    expectMessageCommandOptions({
      action: "timeout",
      guildId: "g",
      userId: "u",
      durationMin: "0",
    });
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it("finalizes only the command's registry when a process root also has hooks", async () => {
    const rootStop = vi.fn();
    initializeGlobalHookRunner(
      createMockPluginRegistry([
        { hookName: "gateway_stop", handler: rootStop, pluginId: "process-root" },
      ]),
    );
    registerStopHook();

    await runSendAction();

    expect(runGatewayStopMock).toHaveBeenCalledOnce();
    expect(rootStop).not.toHaveBeenCalled();
  });

  it("leaves Gateway-owned resources running when the CLI loads no registry", async () => {
    const rootStop = vi.fn();
    initializeGlobalHookRunner(
      createMockPluginRegistry([
        { hookName: "gateway_stop", handler: rootStop, pluginId: "process-root" },
      ]),
    );
    mockChannelExecutionModes({ discord: "gateway" });

    await runSendAction();

    expect(loadPluginRegistryHandleMock).not.toHaveBeenCalled();
    expect(rootStop).not.toHaveBeenCalled();
  });

  it("runs gateway_stop hooks before exit when registered", async () => {
    registerStopHook();
    await runSendAction();

    expect(runGatewayStopMock).toHaveBeenCalledWith({ reason: "cli message action complete" }, {});
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it("skips gateway_stop hooks for read-only message reads", async () => {
    registerStopHook();
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("read", {
        channel: "discord",
        target: "channel:123",
        limit: 1,
      }),
    ).rejects.toThrow("exit");

    expect(runGatewayStopMock).not.toHaveBeenCalled();
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it("bounds gateway_stop hooks so message actions still exit", async () => {
    vi.useFakeTimers();
    try {
      registerStopHook();
      runGatewayStopMock.mockImplementationOnce(() => new Promise(() => {}));
      const runMessageAction = createRunMessageAction();

      const pending = expect(runMessageAction("send", baseSendOptions)).rejects.toThrow("exit");
      await vi.advanceTimersByTimeAsync(2500);
      await pending;

      expect(errorMock).toHaveBeenCalledWith("gateway_stop hook exceeded 2500ms; continuing");
      expect(exitMock).toHaveBeenCalledWith(0);
    } finally {
      vi.useRealTimers();
    }
  });

  it("calls exit(1) when message delivery fails", async () => {
    messageCommandMock.mockRejectedValueOnce(new Error("send failed"));
    await runSendAction();

    expect(errorMock).toHaveBeenCalledWith("send failed");
    expect(exitMock).toHaveBeenCalledOnce();
    expect(exitMock).toHaveBeenCalledWith(1);
  });

  it("runs gateway_stop hooks on failure before exit(1)", async () => {
    registerStopHook();
    messageCommandMock.mockRejectedValueOnce(new Error("send failed"));
    await runSendAction();

    expect(runGatewayStopMock).toHaveBeenCalledWith({ reason: "cli message action complete" }, {});
    expect(exitMock).toHaveBeenCalledWith(1);
  });

  it("runs gateway_stop hooks before exit(1) for a failed broadcast result", async () => {
    const order: string[] = [];
    registerStopHook();
    messageCommandMock.mockResolvedValueOnce({
      kind: "broadcast",
      channel: "telegram",
      action: "broadcast",
      handledBy: "core",
      payload: {
        results: [
          { channel: "telegram", to: "123", ok: true },
          { channel: "telegram", to: "456", ok: false, error: "delivery failed" },
        ],
      },
      dryRun: false,
    });
    runGatewayStopMock.mockImplementationOnce(async () => {
      order.push("stop");
    });
    exitMock.mockImplementationOnce((code: number): never => {
      order.push(`exit:${code}`);
      throw new Error("exit");
    });
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("broadcast", {
        channel: "telegram",
        targets: ["123", "456"],
        message: "hi",
      }),
    ).rejects.toThrow("exit");

    expect(order).toEqual(["stop", "exit:1"]);
    expect(exitMock).not.toHaveBeenCalledWith(0);
  });

  it("logs gateway_stop failure and still exits with success code", async () => {
    registerStopHook();
    runGatewayStopMock.mockRejectedValueOnce(new Error("hook failed"));
    await runSendAction();

    expect(hookErrorMock).toHaveBeenCalledWith(expect.stringContaining("hook failed"));
    expect(exitMock).toHaveBeenCalledWith(0);
  });

  it("logs gateway_stop failure and preserves failure exit code when send fails", async () => {
    registerStopHook();
    messageCommandMock.mockRejectedValueOnce(new Error("send failed"));
    runGatewayStopMock.mockRejectedValueOnce(new Error("hook failed"));
    await runSendAction();

    expect(errorMock).toHaveBeenCalledWith("send failed");
    expect(hookErrorMock).toHaveBeenCalledWith(expect.stringContaining("hook failed"));
    expect(exitMock).toHaveBeenCalledWith(1);
  });

  it("passes action and maps account to accountId", async () => {
    const { runMessageAction } = createMessageCliHelpers("discord");

    await expect(
      runMessageAction("poll", {
        channel: "discord",
        target: "456",
        account: "acct-1",
        message: "hi",
      }),
    ).rejects.toThrow("exit");

    expectMessageCommandOptions({
      action: "poll",
      channel: "discord",
      target: "456",
      accountId: "acct-1",
      message: "hi",
    });
    // account key should be stripped in favor of accountId
    expectNoAccountFieldInPassedOptions();
  });

  it("strips non-string account values instead of passing accountId", async () => {
    const runMessageAction = createRunMessageAction();

    await expect(
      runMessageAction("send", {
        channel: "discord",
        target: "789",
        account: 42,
        message: "hi",
      }),
    ).rejects.toThrow("exit");

    expectMessageCommandOptions({
      action: "send",
      channel: "discord",
      target: "789",
      accountId: undefined,
    });
    expectNoAccountFieldInPassedOptions();
  });
});