Skip to content

Commit 990e8d2

Browse files
authored
feat(presentation): hosted-widget launch via typed web-app actions (#108927)
* feat(presentation): support hosted widget actions * refactor(discord): route widget launches through presentation * chore: keep changelog release-owned * test(interactive): type the invalid web-app boundary case explicitly * test: type web-app action fixtures against the split union The two-member web-app union no longer accepts a distributed type: "url" | "web-app" literal or an empty receipt in typed callbacks; use explicit action casts and the Discord receipt factory.
1 parent eb8cdf6 commit 990e8d2

23 files changed

Lines changed: 528 additions & 66 deletions

‎docs/plugins/message-presentation.md‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,16 @@ type MessagePresentationAction =
7878
decision: "allow-once" | "allow-always" | "deny";
7979
}
8080
| { type: "url"; url: string }
81-
| { type: "web-app"; url: string };
81+
| {
82+
type: "web-app";
83+
url: string;
84+
widgetId?: string;
85+
}
86+
| {
87+
type: "web-app";
88+
url?: string;
89+
widgetId: string;
90+
};
8291

8392
type MessagePresentationButton = {
8493
label: string;
@@ -128,7 +137,11 @@ Button semantics:
128137
the approval service; they must not parse `/approve` command text or infer
129138
kind from the ID.
130139
- `action.type: "url"` opens a normal link.
131-
- `action.type: "web-app"` launches a channel-native web app.
140+
- `action.type: "web-app"` launches a channel-native web app. Set `url` for a
141+
URL-backed app or `widgetId` for an OpenClaw-hosted widget whose launch
142+
mechanics are owned by the channel; at least one is required. When both are
143+
present, a channel can prefer its native hosted-widget launch and use the URL
144+
where that mechanism is unavailable.
132145
- `value` is the legacy opaque callback value. New controls should use `action`
133146
so channel plugins can map commands and callbacks without guessing from text.
134147
- `url`, `webApp`, and `web_app` remain accepted as deprecated boundary inputs.
@@ -501,9 +514,10 @@ keeping opaque callback data private:
501514
- **`approval`-typed actions** render label-only. Approval IDs and decisions are
502515
transport data and are not exposed through generic scalar helpers or fallback
503516
text.
504-
- **`url` / `web-app` actions** and deprecated **`url` / `webApp` / `web_app`**
505-
inputs render the URL text alongside the button label, since the URL is
506-
user-facing.
517+
- **`url` actions**, URL-backed **`web-app` actions**, and deprecated **`url` /
518+
`webApp` / `web_app`** inputs render the URL text alongside the button label,
519+
since the URL is user-facing. Hosted-widget-only actions render label-only on
520+
channels without a native widget launch.
507521
- **Select options** render as label-only. The underlying option value is not
508522
exposed in fallback text.
509523

‎extensions/discord/src/activities/interaction.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
createInternalTestClient,
99
} from "../internal/test-builders.test-support.js";
1010
import type { AgentComponentContext } from "../monitor/agent-components.types.js";
11+
import { buildDiscordPresentationComponents } from "../shared-interactive.js";
1112
import { createDiscordActivityButton } from "./interaction.js";
1213
import { setDiscordActivitiesRuntime } from "./runtime.js";
1314
import {
@@ -73,8 +74,25 @@ describe("Discord Activity interaction", () => {
7374
});
7475
const launchActivity = vi.fn(async () => undefined);
7576
const interaction = { launchActivity } as unknown as ButtonInteraction;
77+
const rendered = buildDiscordPresentationComponents({
78+
blocks: [
79+
{
80+
type: "buttons",
81+
buttons: [
82+
{
83+
label: "Open widget",
84+
action: { type: "web-app", widgetId: "AAAAAAAAAAAAAAAAAAAAAA" },
85+
},
86+
],
87+
},
88+
],
89+
});
90+
const actionBlock = rendered?.blocks?.find((block) => block.type === "actions");
91+
const customId =
92+
actionBlock?.type === "actions" ? actionBlock.buttons?.[0]?.internalCustomId : "";
93+
const data = button?.customIdParser(customId ?? "").data ?? {};
7694

77-
await button?.run(interaction, { widgetId: "AAAAAAAAAAAAAAAAAAAAAA" });
95+
await button?.run(interaction, data);
7896

7997
expect(authorize).toHaveBeenCalledOnce();
8098
expect(launchActivity).toHaveBeenCalledOnce();

‎extensions/discord/src/activities/tool.test.ts‎

Lines changed: 77 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import type { OpenClawPluginToolContext } from "openclaw/plugin-sdk/plugin-entry";
22
import { describe, expect, it, vi } from "vitest";
3-
import { buildDiscordActivityCustomId } from "../component-custom-id.js";
4-
import type { sendMessageDiscord } from "../send.js";
3+
import {
4+
buildDiscordActivityCustomId,
5+
parseDiscordActivityCustomIdForInteraction,
6+
} from "../component-custom-id.js";
7+
import { buildDiscordComponentMessage } from "../components.js";
8+
import type { sendDiscordComponentMessage } from "../send.components.js";
9+
import { createDiscordSendReceipt } from "../send.receipt.js";
510
import { createActivityTestRuntime } from "./test-helpers.test-support.js";
611
import { createDiscordWidgetTool } from "./tool.js";
712

@@ -25,14 +30,14 @@ describe("discord_widget", () => {
2530

2631
it("stores a wrapped widget and posts its launch button", async () => {
2732
const runtime = createActivityTestRuntime();
28-
const send = vi.fn(async (..._args: Parameters<typeof sendMessageDiscord>) => ({
33+
const send = vi.fn(async (..._args: Parameters<typeof sendDiscordComponentMessage>) => ({
2934
messageId: "message-1",
3035
channelId: "987654321",
3136
receipt: {},
3237
}));
3338
const tool = createDiscordWidgetTool(discordContext(), {
3439
runtime,
35-
sendMessage: send as unknown as typeof sendMessageDiscord,
40+
sendComponentMessage: send as unknown as typeof sendDiscordComponentMessage,
3641
now: () => 7,
3742
});
3843
if (!tool) {
@@ -56,24 +61,38 @@ describe("discord_widget", () => {
5661
});
5762
expect(stored?.html).toContain("<!doctype html>");
5863
expect(stored?.html).toContain("<button");
59-
const options = send.mock.calls[0]?.[2] as { components?: Array<{ serialize(): unknown }> };
60-
expect(send).toHaveBeenCalledWith("channel:987654321", "Status", expect.any(Object));
61-
expect(options.components?.[0]?.serialize()).toEqual({
62-
type: 1,
63-
components: [
64+
const spec = send.mock.calls[0]?.[1];
65+
const customId = buildDiscordActivityCustomId(details.widgetId);
66+
expect(send).toHaveBeenCalledWith("channel:987654321", expect.any(Object), expect.any(Object));
67+
expect(send.mock.calls[0]?.[2]).toMatchObject({ allowedMentions: { parse: [] } });
68+
if (!spec) {
69+
throw new Error("expected Discord component spec");
70+
}
71+
expect(spec).toEqual({
72+
text: "Status",
73+
blocks: [
6474
{
65-
type: 2,
66-
style: 1,
67-
custom_id: buildDiscordActivityCustomId(details.widgetId),
68-
label: "Open widget",
75+
type: "actions",
76+
buttons: [
77+
{
78+
label: "Open widget",
79+
style: "secondary",
80+
internalCustomId: customId,
81+
},
82+
],
6983
},
7084
],
7185
});
86+
expect(JSON.stringify(buildDiscordComponentMessage({ spec }).components)).toContain(customId);
87+
expect(parseDiscordActivityCustomIdForInteraction(customId)).toEqual({
88+
key: "ocactivity",
89+
data: { widgetId: details.widgetId },
90+
});
7291
});
7392

7493
it("resolves a provider-prefixed forum thread target", async () => {
7594
const runtime = createActivityTestRuntime();
76-
const send = vi.fn(async (..._args: Parameters<typeof sendMessageDiscord>) => ({
95+
const send = vi.fn(async (..._args: Parameters<typeof sendDiscordComponentMessage>) => ({
7796
messageId: "message-1",
7897
channelId: "987654321",
7998
receipt: {},
@@ -85,7 +104,7 @@ describe("discord_widget", () => {
85104
}),
86105
{
87106
runtime,
88-
sendMessage: send as unknown as typeof sendMessageDiscord,
107+
sendComponentMessage: send as unknown as typeof sendDiscordComponentMessage,
89108
},
90109
);
91110
if (!tool) {
@@ -98,20 +117,24 @@ describe("discord_widget", () => {
98117
});
99118

100119
expect(result.details).toMatchObject({ channelId: "987654321" });
101-
expect(send).toHaveBeenCalledWith("channel:987654321", "Forum widget", expect.any(Object));
120+
expect(send).toHaveBeenCalledWith(
121+
"channel:987654321",
122+
expect.objectContaining({ text: "Forum widget" }),
123+
expect.any(Object),
124+
);
102125
});
103126

104127
it("keeps full documents unchanged and rejects oversized HTML", async () => {
105128
const document = "<!doctype html><html><body>full</body></html>";
106129
const runtime = createActivityTestRuntime();
107-
const send = vi.fn(async (..._args: Parameters<typeof sendMessageDiscord>) => ({
130+
const send = vi.fn(async (..._args: Parameters<typeof sendDiscordComponentMessage>) => ({
108131
messageId: "message-1",
109132
channelId: "987654321",
110133
receipt: {},
111134
}));
112135
const tool = createDiscordWidgetTool(discordContext(), {
113136
runtime,
114-
sendMessage: send as unknown as typeof sendMessageDiscord,
137+
sendComponentMessage: send as unknown as typeof sendDiscordComponentMessage,
115138
});
116139
if (!tool) {
117140
throw new Error("expected Discord widget tool");
@@ -143,8 +166,8 @@ describe("discord_widget", () => {
143166
const failure = new Error("send failed");
144167
const send = vi.fn(async () => {
145168
throw failure;
146-
}) as unknown as typeof sendMessageDiscord;
147-
const tool = createDiscordWidgetTool(discordContext(), { runtime, sendMessage: send });
169+
}) as unknown as typeof sendDiscordComponentMessage;
170+
const tool = createDiscordWidgetTool(discordContext(), { runtime, sendComponentMessage: send });
148171
if (!tool) {
149172
throw new Error("expected Discord widget tool");
150173
}
@@ -157,10 +180,42 @@ describe("discord_widget", () => {
157180
).resolves.toMatchObject({ id: existingId, widget: { title: "Existing" } });
158181
});
159182

183+
it("keeps a widget when component bookkeeping fails after delivery", async () => {
184+
const runtime = createActivityTestRuntime();
185+
const failure = new Error("registry failed");
186+
const send = vi.fn(async (...args: Parameters<typeof sendDiscordComponentMessage>) => {
187+
await args[2].onDeliveryResult?.({
188+
messageId: "delivered-message",
189+
channelId: "987654321",
190+
receipt: createDiscordSendReceipt({
191+
platformMessageIds: ["delivered-message"],
192+
channelId: "987654321",
193+
kind: "text",
194+
}),
195+
});
196+
throw failure;
197+
}) as unknown as typeof sendDiscordComponentMessage;
198+
const tool = createDiscordWidgetTool(discordContext(), { runtime, sendComponentMessage: send });
199+
if (!tool) {
200+
throw new Error("expected Discord widget tool");
201+
}
202+
203+
const result = await tool.execute("delivered-send", {
204+
html: "<p>delivered</p>",
205+
title: "Delivered",
206+
});
207+
const details = result.details as { widgetId: string; messageId: string };
208+
209+
expect(details.messageId).toBe("delivered-message");
210+
await expect(runtime.store.lookupWidget(details.widgetId)).resolves.toMatchObject({
211+
title: "Delivered",
212+
});
213+
});
214+
160215
it("requires a concrete channel target", async () => {
161216
const tool = createDiscordWidgetTool(discordContext({ nativeChannelId: undefined }), {
162217
runtime: createActivityTestRuntime(),
163-
sendMessage: vi.fn() as unknown as typeof sendMessageDiscord,
218+
sendComponentMessage: vi.fn() as unknown as typeof sendDiscordComponentMessage,
164219
});
165220
if (!tool) {
166221
throw new Error("expected Discord widget tool");
@@ -178,7 +233,7 @@ describe("discord_widget", () => {
178233
}),
179234
{
180235
runtime: createActivityTestRuntime(),
181-
sendMessage: vi.fn() as unknown as typeof sendMessageDiscord,
236+
sendComponentMessage: vi.fn() as unknown as typeof sendDiscordComponentMessage,
182237
},
183238
);
184239
if (!tool) {

‎extensions/discord/src/activities/tool.ts‎

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,8 @@ import {
99
} from "openclaw/plugin-sdk/widget-html";
1010
import { Type } from "typebox";
1111
import { resolveDiscordAccount } from "../accounts.js";
12-
import { buildDiscordActivityCustomId } from "../component-custom-id.js";
13-
import { Button, Row } from "../internal/discord.js";
14-
import { sendMessageDiscord } from "../send.js";
12+
import { sendDiscordComponentMessage } from "../send.components.js";
13+
import { buildDiscordPresentationComponents } from "../shared-interactive.js";
1514
import { resolveDiscordChannelId as resolveDiscordTargetChannelId } from "../target-parsing.js";
1615
import type { DiscordActivitiesRuntime } from "./runtime.js";
1716

@@ -23,15 +22,6 @@ const DiscordWidgetParameters = Type.Object({
2322
button_label: Type.Optional(Type.String({ minLength: 1, maxLength: 80 })),
2423
});
2524

26-
class DiscordWidgetLaunchButton extends Button {
27-
constructor(
28-
readonly customId: string,
29-
readonly label: string,
30-
) {
31-
super();
32-
}
33-
}
34-
3525
function currentConfig(context: OpenClawPluginToolContext, runtime: DiscordActivitiesRuntime) {
3626
return (
3727
context.getRuntimeConfig?.() ??
@@ -64,7 +54,7 @@ function buildDiscordWidgetDocument(title: string, html: string): string {
6454

6555
type DiscordWidgetToolDeps = {
6656
runtime: DiscordActivitiesRuntime;
67-
sendMessage?: typeof sendMessageDiscord;
57+
sendComponentMessage?: typeof sendDiscordComponentMessage;
6858
now?: () => number;
6959
};
7060

@@ -120,24 +110,43 @@ export function createDiscordWidgetTool(
120110
accountId: account.accountId,
121111
createdAt: (deps.now ?? Date.now)(),
122112
});
123-
let result: Awaited<ReturnType<typeof sendMessageDiscord>>;
113+
let result: Awaited<ReturnType<typeof sendDiscordComponentMessage>>;
114+
let deliveredResult: Awaited<ReturnType<typeof sendDiscordComponentMessage>> | undefined;
124115
try {
125-
result = await (deps.sendMessage ?? sendMessageDiscord)(`channel:${channelId}`, title, {
126-
cfg: cfg as OpenClawConfig,
127-
accountId: account.accountId,
128-
components: [
129-
new Row([
130-
new DiscordWidgetLaunchButton(
131-
buildDiscordActivityCustomId(widgetId),
132-
buttonLabel.trim(),
133-
),
134-
]),
116+
const components = buildDiscordPresentationComponents({
117+
blocks: [
118+
{
119+
type: "buttons",
120+
buttons: [
121+
{
122+
label: buttonLabel.trim(),
123+
action: { type: "web-app", widgetId },
124+
},
125+
],
126+
},
135127
],
136-
allowedMentions: { parse: [] },
137128
});
129+
if (!components) {
130+
throw new Error("Discord widget launch button could not be rendered");
131+
}
132+
result = await (deps.sendComponentMessage ?? sendDiscordComponentMessage)(
133+
`channel:${channelId}`,
134+
{ ...components, text: title },
135+
{
136+
cfg: cfg as OpenClawConfig,
137+
accountId: account.accountId,
138+
allowedMentions: { parse: [] },
139+
onDeliveryResult: (deliveryResult) => {
140+
deliveredResult = deliveryResult;
141+
},
142+
},
143+
);
138144
} catch (error) {
139-
await deps.runtime.store.deleteWidget(widgetId);
140-
throw error;
145+
if (!deliveredResult) {
146+
await deps.runtime.store.deleteWidget(widgetId);
147+
throw error;
148+
}
149+
result = deliveredResult;
141150
}
142151
return jsonResult({ widgetId, messageId: result.messageId, channelId: result.channelId });
143152
},

‎extensions/discord/src/component-custom-id.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ export const DISCORD_MODAL_CUSTOM_ID_KEY = "ocmodal";
1111
const DISCORD_ACTIVITY_CUSTOM_ID_KEY = "ocactivity";
1212
const ENCODED_CUSTOM_ID_VERSION = "1";
1313

14+
export function isValidDiscordActivityWidgetId(widgetId: string): boolean {
15+
return /^[A-Za-z0-9_-]{22}$/.test(widgetId);
16+
}
17+
1418
export function buildDiscordActivityCustomId(widgetId: string): string {
1519
return `${DISCORD_ACTIVITY_CUSTOM_ID_KEY}:v=${ENCODED_CUSTOM_ID_VERSION};wid=${widgetId}`;
1620
}
@@ -21,7 +25,7 @@ export function parseDiscordActivityCustomId(id: string): { widgetId: string } |
2125
parsed.key !== DISCORD_ACTIVITY_CUSTOM_ID_KEY ||
2226
parsed.data.v !== ENCODED_CUSTOM_ID_VERSION ||
2327
typeof parsed.data.wid !== "string" ||
24-
!/^[A-Za-z0-9_-]{22}$/.test(parsed.data.wid)
28+
!isValidDiscordActivityWidgetId(parsed.data.wid)
2529
) {
2630
return null;
2731
}

0 commit comments

Comments
 (0)