Skip to content

Commit 9f0c82f

Browse files
committed
refactor(cli): share message payload projections
1 parent f61666a commit 9f0c82f

6 files changed

Lines changed: 193 additions & 108 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2546,8 +2546,8 @@ src/commands/export-trajectory.ts 1
25462546
src/commands/gateway-health-auth-diagnostic.ts 1
25472547
src/commands/gateway-presence.ts 1
25482548
src/commands/gateway-status/helpers.ts 11
2549-
src/commands/message-format.ts 20
2550-
src/commands/message.ts 4
2549+
src/commands/message-format.ts 17
2550+
src/commands/message.ts 2
25512551
src/commands/models/fallbacks-shared.ts 2
25522552
src/commands/models/list.model-projection.ts 1
25532553
src/commands/models/list.persisted-catalog.ts 2

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

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,25 @@ describe("renderPaginationHint", () => {
243243
});
244244

245245
describe("formatMessageCliText send results", () => {
246+
it("prefers and trims a direct plugin payload message ID", () => {
247+
const result = {
248+
kind: "send",
249+
action: "send",
250+
channel: "directchat",
251+
to: "room-1",
252+
handledBy: "plugin",
253+
payload: {
254+
messageId: " direct-id ",
255+
result: { messageId: "nested-id" },
256+
},
257+
dryRun: false,
258+
} satisfies MessageActionResult;
259+
260+
expect(formatMessageCliText(result)).toEqual([
261+
"✅ Sent via Direct Chat. Message ID: direct-id",
262+
]);
263+
});
264+
246265
it.each([
247266
{
248267
status: "suppressed" as const,
@@ -294,6 +313,74 @@ describe("formatMessageCliText send results", () => {
294313
);
295314
});
296315

316+
describe("formatMessageCliText payload scalars", () => {
317+
it("keeps alias reads lazy after the first nonempty string", () => {
318+
const reads: string[] = [];
319+
const message = Object.create(null) as Record<string, unknown>;
320+
Object.defineProperties(message, {
321+
id: {
322+
enumerable: true,
323+
get: () => {
324+
reads.push("id");
325+
return reads.length === 1 ? "first-id" : "second-id";
326+
},
327+
},
328+
ts: {
329+
enumerable: true,
330+
get: () => {
331+
reads.push("ts");
332+
throw new Error("later alias must not be read");
333+
},
334+
},
335+
authorTag: { enumerable: true, value: "alice" },
336+
timestamp: { enumerable: true, value: "now" },
337+
content: { enumerable: true, value: "hello" },
338+
});
339+
340+
const output = textJoined(formatMessageCliText(readResultPayload({ messages: [message] })));
341+
expect(output).toContain("second-id");
342+
expect(output).not.toContain("first-id");
343+
expect(reads).toEqual(["id", "id"]);
344+
});
345+
346+
it("preserves generic object primitive summaries", () => {
347+
const result = {
348+
kind: "action",
349+
channel: "directchat",
350+
action: "channel-info",
351+
handledBy: "plugin",
352+
payload: {
353+
undef: undefined,
354+
nil: null,
355+
array: [1, 2],
356+
object: {},
357+
function: () => undefined,
358+
bigint: 42n,
359+
symbol: Symbol("proof"),
360+
string: " keep ",
361+
number: -3,
362+
boolean: false,
363+
},
364+
dryRun: false,
365+
} satisfies MessageActionResult;
366+
367+
const output = textJoined(formatMessageCliText(result));
368+
for (const expected of [
369+
"null",
370+
"2 items",
371+
"object",
372+
"function",
373+
"42",
374+
"Symbol(proof)",
375+
"keep",
376+
"-3",
377+
"false",
378+
]) {
379+
expect(output).toContain(expected);
380+
}
381+
});
382+
});
383+
297384
describe("formatMessageCliText provider-reported failures", () => {
298385
it.each([
299386
["disabled reaction", "react", { ok: false, hint: "Reactions are disabled." }, "disabled"],

‎src/commands/message-format.ts‎

Lines changed: 40 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
/** Human-readable formatter for `openclaw message` action results. */
2-
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
32
import { normalizeStringEntries } from "@openclaw/normalization-core/string-normalization";
43
import { getTerminalTableWidth, renderTable } from "../../packages/terminal-core/src/table.js";
54
import { isRich, theme } from "../../packages/terminal-core/src/theme.js";
@@ -8,6 +7,7 @@ import type { ChannelId } from "../channels/plugins/types.public.js";
87
import type { OutboundDeliveryResult } from "../infra/outbound/deliver.js";
98
import { formatGatewaySummary, formatOutboundDeliverySummary } from "../infra/outbound/format.js";
109
import {
10+
resolveMessageActionMessageId,
1111
resolveMessageActionOutcome,
1212
type MessageActionResult,
1313
} from "../infra/outbound/message-action-contracts.js";
@@ -17,24 +17,17 @@ import { shortenText } from "./text-format.js";
1717
const resolveChannelLabel = (channel: ChannelId) =>
1818
getLoadedChannelPlugin(channel)?.meta.label ?? channel;
1919

20-
function extractMessageId(payload: unknown): string | null {
21-
if (!payload || typeof payload !== "object") {
22-
return null;
23-
}
24-
const direct = (payload as { messageId?: unknown }).messageId;
25-
const directId = normalizeOptionalString(direct);
26-
if (directId) {
27-
return directId;
28-
}
29-
const result = (payload as { result?: unknown }).result;
30-
if (result && typeof result === "object") {
31-
const nested = (result as { messageId?: unknown }).messageId;
32-
const nestedId = normalizeOptionalString(nested);
33-
if (nestedId) {
34-
return nestedId;
20+
function firstNonemptyString(
21+
record: Record<string, unknown> | undefined,
22+
...keys: string[]
23+
): string {
24+
for (const key of keys) {
25+
const value = typeof record?.[key] === "string" && record?.[key];
26+
if (value) {
27+
return value as string; // SAFETY: Preserve the old second accessor read after its string check.
3528
}
3629
}
37-
return null;
30+
return "";
3831
}
3932

4033
type FormatOpts = {
@@ -43,6 +36,25 @@ type FormatOpts = {
4336
displayLimit?: number;
4437
};
4538

39+
function renderSummaryValue(value: unknown): string {
40+
if (value == null) {
41+
return "null";
42+
}
43+
if (Array.isArray(value)) {
44+
return `${value.length} items`;
45+
}
46+
switch (typeof value) {
47+
case "string":
48+
case "number":
49+
case "boolean":
50+
case "bigint":
51+
case "symbol":
52+
return String(value);
53+
default:
54+
return typeof value;
55+
}
56+
}
57+
4658
function renderObjectSummary(payload: unknown, opts: FormatOpts): string {
4759
if (!payload || typeof payload !== "object") {
4860
return String(payload);
@@ -54,29 +66,7 @@ function renderObjectSummary(payload: unknown, opts: FormatOpts): string {
5466
}
5567

5668
const rows = keys.slice(0, 20).map((k) => {
57-
const v = obj[k];
58-
const value =
59-
v == null
60-
? "null"
61-
: Array.isArray(v)
62-
? `${v.length} items`
63-
: typeof v === "object"
64-
? "object"
65-
: typeof v === "string"
66-
? v
67-
: typeof v === "number"
68-
? String(v)
69-
: typeof v === "boolean"
70-
? v
71-
? "true"
72-
: "false"
73-
: typeof v === "bigint"
74-
? v.toString()
75-
: typeof v === "symbol"
76-
? v.toString()
77-
: typeof v === "function"
78-
? "function"
79-
: "unknown";
69+
const value = renderSummaryValue(obj[k]);
8070
return { Key: k, Value: shortenText(value, 96) };
8171
});
8272
return renderTable({
@@ -93,25 +83,14 @@ function renderMessageList(messages: unknown[], opts: FormatOpts, emptyLabel: st
9383
const cap = opts.displayLimit ?? 25;
9484
const rows = messages.slice(0, cap).map((m) => {
9585
const msg = m as Record<string, unknown>;
96-
const id =
97-
(typeof msg.id === "string" && msg.id) ||
98-
(typeof msg.ts === "string" && msg.ts) ||
99-
(typeof msg.messageId === "string" && msg.messageId) ||
100-
"";
86+
const id = firstNonemptyString(msg, "id", "ts", "messageId");
10187
const authorObj = msg.author as Record<string, unknown> | undefined;
10288
const author =
103-
(typeof msg.authorTag === "string" && msg.authorTag) ||
104-
(typeof authorObj?.username === "string" && authorObj.username) ||
105-
(typeof msg.user === "string" && msg.user) ||
106-
"";
107-
const time =
108-
(typeof msg.timestamp === "string" && msg.timestamp) ||
109-
(typeof msg.ts === "string" && msg.ts) ||
110-
"";
111-
const text =
112-
(typeof msg.content === "string" && msg.content) ||
113-
(typeof msg.text === "string" && msg.text) ||
114-
"";
89+
firstNonemptyString(msg, "authorTag") ||
90+
firstNonemptyString(authorObj, "username") ||
91+
firstNonemptyString(msg, "user");
92+
const time = firstNonemptyString(msg, "timestamp", "ts");
93+
const text = firstNonemptyString(msg, "content", "text");
11594
return {
11695
Time: shortenText(time, 28),
11796
Author: shortenText(author, 22),
@@ -169,10 +148,7 @@ function renderReactions(payload: unknown, opts: FormatOpts): string | null {
169148
const entry = r as Record<string, unknown>;
170149
const emojiObj = entry.emoji as Record<string, unknown> | undefined;
171150
const emoji =
172-
(typeof emojiObj?.raw === "string" && emojiObj.raw) ||
173-
(typeof entry.name === "string" && entry.name) ||
174-
(typeof entry.emoji === "string" && entry.emoji) ||
175-
"";
151+
firstNonemptyString(emojiObj, "raw") || firstNonemptyString(entry, "name", "emoji");
176152
const count = typeof entry.count === "number" ? String(entry.count) : "";
177153
const userList = Array.isArray(entry.users)
178154
? (entry.users as unknown[])
@@ -185,12 +161,7 @@ function renderReactions(payload: unknown, opts: FormatOpts): string | null {
185161
return "";
186162
}
187163
const user = u as Record<string, unknown>;
188-
return (
189-
(typeof user.tag === "string" && user.tag) ||
190-
(typeof user.username === "string" && user.username) ||
191-
(typeof user.id === "string" && user.id) ||
192-
""
193-
);
164+
return firstNonemptyString(user, "tag", "username", "id");
194165
})
195166
.filter(Boolean)
196167
: [];
@@ -309,7 +280,7 @@ export function formatMessageCliText(
309280
}
310281

311282
const label = resolveChannelLabel(result.channel);
312-
const msgId = extractMessageId(result.payload);
283+
const msgId = resolveMessageActionMessageId(result.payload);
313284
return [ok(`✅ Sent via ${label}.${msgId ? ` Message ID: ${msgId}` : ""}`)];
314285
}
315286

@@ -350,7 +321,7 @@ export function formatMessageCliText(
350321
}
351322

352323
const label = resolveChannelLabel(result.channel);
353-
const msgId = extractMessageId(result.payload);
324+
const msgId = resolveMessageActionMessageId(result.payload);
354325
return [ok(`✅ Poll sent via ${label}.${msgId ? ` Message ID: ${msgId}` : ""}`)];
355326
}
356327

‎src/commands/message.test.ts‎

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -576,20 +576,51 @@ describe("messageCommand", () => {
576576
expect(actionCall.params.pollQuestion).toBe("Ship it?");
577577
});
578578

579-
it("includes a stable top-level messageId in JSON output", async () => {
580-
runMessageActionMock.mockResolvedValueOnce({
581-
kind: "send",
582-
channel: "discord",
583-
action: "send",
584-
to: "channel:general",
585-
handledBy: "plugin",
579+
it.each([
580+
{
581+
name: "nested",
586582
payload: {
587583
ok: true,
588584
result: {
589585
messageId: "msg-json-1",
590586
channelId: "general",
591587
},
592-
} as { ok: boolean } & Record<string, unknown>,
588+
},
589+
expectedMessageId: "msg-json-1",
590+
expectedPayload: {
591+
ok: true,
592+
result: {
593+
messageId: "msg-json-1",
594+
channelId: "general",
595+
},
596+
},
597+
},
598+
{
599+
name: "direct-before-nested",
600+
payload: {
601+
messageId: " direct-id ",
602+
result: { messageId: "nested-id" },
603+
},
604+
expectedMessageId: "direct-id",
605+
expectedPayload: {
606+
messageId: " direct-id ",
607+
result: { messageId: "nested-id" },
608+
},
609+
},
610+
{
611+
name: "array object",
612+
payload: Object.assign([], { messageId: " array-id " }),
613+
expectedMessageId: "array-id",
614+
expectedPayload: [],
615+
},
616+
])("includes a stable top-level messageId from a $name payload", async (testCase) => {
617+
runMessageActionMock.mockResolvedValueOnce({
618+
kind: "send",
619+
channel: "discord",
620+
action: "send",
621+
to: "channel:general",
622+
handledBy: "plugin",
623+
payload: testCase.payload,
593624
dryRun: false,
594625
});
595626

@@ -600,14 +631,8 @@ describe("messageCommand", () => {
600631

601632
const output = vi.mocked(runtime.log).mock.calls[0]?.[0];
602633
const json = JSON.parse(String(output)) as { messageId?: string; payload?: unknown };
603-
expect(json.messageId).toBe("msg-json-1");
604-
expect(json.payload).toEqual({
605-
ok: true,
606-
result: {
607-
messageId: "msg-json-1",
608-
channelId: "general",
609-
},
610-
});
634+
expect(json.messageId).toBe(testCase.expectedMessageId);
635+
expect(json.payload).toEqual(testCase.expectedPayload);
611636
expect(json).not.toHaveProperty("ok");
612637
});
613638

0 commit comments

Comments
 (0)