Files
openclaw/extensions/matrix/src/approval-handler.runtime.test.ts
Peter Steinberger 7a456e362d feat(channels): add typed cross-surface approval actions (#103679)
* fix(gateway): approval registry hardening and protocol-surface follow-ups

Follow-up delta to the merged #103579 head, rebased onto current main:
- gateway-protocol wire types derive from owner-module schema consts
  (types.ts tombstone) and ProtocolSchemas leaves the package index so the
  public plugin-sdk d.ts graph tree-shakes the registry declaration
- approval access authority follows the operator.approvals scope tier with
  reviewerDeviceIds as the opt-in restriction (cross-surface
  first-answer-wins; requester identity gates only legacy adapters)
- plugin node.invoke approvals register directly so unrenderable
  presentations fail closed before request routing
- exec-approval manager reconciliation with #103515 revocation hardening
  (resolution source attribution, one-shot ask-fallback consumption)
- surface-report pins and plugin-sdk API baseline refreshed; Swift models
  regenerated

* feat(channels): add typed operator approval actions

Squash-rebased #103679 segment onto the durable-approval-registry tip on
current main. Typed approval/command/select presentation actions replace
raw-string inference across slack/telegram/discord/matrix/imessage/whatsapp,
approval.resolve carries an explicit kind, and channel adapters map native
callback envelopes through the typed action registry.

Drift reconciliation: deprecated buildExecApprovalInteractiveReply assertions
dropped (#104650 removed the shims); worker_environments bootstrap-column
migration kept alongside the approval resolution_ref backfill; plugin-sdk API
baseline regenerated.

(cherry picked from commit 68765a5d39d2118c88a7a54d00387337912d4494)
(cherry picked from commit 8642ac12af142e4b751f4f30d4b114615e7e5f66)
(cherry picked from commit 036c4bc39499925fc03de16ec9302e346769350a)
(cherry picked from commit 19dc350d6bc34e29a5169c6bc80971b0ad12adde)
(cherry picked from commit fc978b0bad86aef421c79f6a211b25cc1b743c01)
(cherry picked from commit 10de4d1ed5071f9be6ad1ee5d1e32c0fa8c9d11c)
(cherry picked from commit 9a664ced1b1fa740172b258f355f1a82925ae41c)
(cherry picked from commit c5ff69abbf444139e9e007bfa45beb0f00ffea54)
(cherry picked from commit d466a80795)
(cherry picked from commit f5b4fe40dd5c961322f8553cc80b2fdfb3f6503e)
(cherry picked from commit 7340b4749a4cc4c72f7a41cce1bc9cb550cae038)
(cherry picked from commit a151f41808f23ae60b10305ccd2bc959b9169a86)

* fix(approvals): preserve typed transport ownership

* test(imessage): narrow chunked approval text

* refactor(protocol): remove retired type tombstone

* fix(plugin-sdk): align surface budgets after rebase

* docs(changelog): note typed operator approvals

* docs(changelog): defer typed approval release note
2026-07-11 18:31:05 -07:00

595 lines
17 KiB
TypeScript

// Matrix tests cover approval handler plugin behavior.
import type {
ExecApprovalRequest,
PluginApprovalRequest,
} from "openclaw/plugin-sdk/approval-runtime";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { matrixApprovalNativeRuntime } from "./approval-handler.runtime.js";
import {
clearMatrixApprovalReactionTargetsForTest,
resolveMatrixApprovalReactionTargetWithPersistence as resolveMatrixApprovalReactionTargetWithPersistenceRaw,
} from "./approval-reactions.js";
type ResolveTargetParams = Parameters<
typeof resolveMatrixApprovalReactionTargetWithPersistenceRaw
>[0];
function resolveMatrixApprovalReactionTargetWithPersistence(
params: Omit<ResolveTargetParams, "accountId"> & { accountId?: string },
) {
const { accountId = "default", ...target } = params;
return resolveMatrixApprovalReactionTargetWithPersistenceRaw({
...target,
accountId,
});
}
type MatrixDeliverPendingParams = Parameters<
typeof matrixApprovalNativeRuntime.transport.deliverPending
>[0];
type MatrixPendingApprovalView = MatrixDeliverPendingParams["view"];
type MatrixPendingExecApprovalView = Extract<MatrixPendingApprovalView, { approvalKind: "exec" }>;
type MatrixPendingPluginApprovalView = Extract<
MatrixPendingApprovalView,
{ approvalKind: "plugin" }
>;
const MATRIX_APPROVAL_METADATA_KEY = "com.openclaw.approval";
function expectRecordFields(value: unknown, expected: Record<string, unknown>) {
if (!value || typeof value !== "object") {
throw new Error("Expected record");
}
const actual = value as Record<string, unknown>;
for (const [key, expectedValue] of Object.entries(expected)) {
expect(actual[key]).toEqual(expectedValue);
}
return actual;
}
function mockCall<T extends readonly unknown[]>(mock: { mock: { calls: T[] } }, index = 0) {
return mock.mock.calls.at(index);
}
function buildMatrixReceipt(messageIds: readonly string[], roomId = "!room:example.org") {
return {
primaryPlatformMessageId: messageIds[0],
platformMessageIds: [...messageIds],
parts: messageIds.map((messageId, index) => ({
platformMessageId: messageId,
kind: "text" as const,
index,
raw: {
channel: "matrix",
messageId,
roomId,
},
})),
sentAt: 100,
raw: messageIds.map((messageId) => ({
channel: "matrix",
messageId,
roomId,
})),
};
}
function buildMatrixApprovalRoomTarget(
roomId: string,
): MatrixDeliverPendingParams["plannedTarget"] {
return {
surface: "approver-dm",
target: {
to: `room:${roomId}`,
},
reason: "preferred",
};
}
// Pending approvals expire in the future; the reaction target store TTLs its
// memory layer from `view.expiresAtMs - now`, so epoch-past fixtures would
// evict the mapping before assertions run.
const TEST_APPROVAL_EXPIRES_AT_MS = Date.now() + 5 * 60_000;
function buildExecApprovalView(
overrides: Partial<MatrixPendingExecApprovalView> = {},
): MatrixPendingExecApprovalView {
return {
approvalKind: "exec",
approvalId: "req-1",
phase: "pending",
title: "Exec Approval Required",
description: "A command needs your approval.",
metadata: [],
ask: "on-request",
agentId: "agent-1",
commandText: "echo hi",
commandPreview: "echo hi",
cwd: "/repo",
host: "gateway",
actions: [
{
decision: "allow-once",
label: "Allow Once",
style: "success",
command: "/approve req-1 allow-once",
},
{
decision: "deny",
label: "Deny",
style: "danger",
command: "/approve req-1 deny",
},
],
expiresAtMs: TEST_APPROVAL_EXPIRES_AT_MS,
...overrides,
};
}
function buildPluginApprovalView(
overrides: Partial<MatrixPendingPluginApprovalView> = {},
): MatrixPendingPluginApprovalView {
return {
approvalKind: "plugin",
approvalId: "plugin:req-1",
phase: "pending",
title: "Plugin Approval Required",
description: "Approve the tool call.",
metadata: [],
agentId: "agent-1",
pluginId: "ops",
toolName: "deploy",
severity: "critical",
actions: [
{
decision: "allow-once",
label: "Allow Once",
style: "success",
command: "/approve plugin:req-1 allow-once",
},
],
expiresAtMs: TEST_APPROVAL_EXPIRES_AT_MS,
...overrides,
};
}
async function buildPendingPayload(view: MatrixPendingApprovalView) {
const request =
view.approvalKind === "plugin"
? ({
id: view.approvalId,
request: {
title: view.title,
description: view.description ?? "",
severity: view.severity,
toolName: view.toolName ?? undefined,
pluginId: view.pluginId ?? undefined,
agentId: view.agentId ?? undefined,
},
createdAtMs: 0,
expiresAtMs: view.expiresAtMs,
} satisfies PluginApprovalRequest)
: ({
id: view.approvalId,
request: {
command: view.commandText,
cwd: view.cwd ?? undefined,
host: view.host ?? undefined,
agentId: view.agentId ?? undefined,
},
createdAtMs: 0,
expiresAtMs: view.expiresAtMs,
} satisfies ExecApprovalRequest);
return await matrixApprovalNativeRuntime.presentation.buildPendingPayload({
cfg: {} as never,
accountId: "default",
context: { client: {} as never },
request,
approvalKind: view.approvalKind,
nowMs: 100,
view,
});
}
describe("matrixApprovalNativeRuntime", () => {
beforeEach(() => {
clearMatrixApprovalReactionTargetsForTest();
});
it("sends versioned Matrix approval content with pending exec approvals", async () => {
const sendSingleTextMessage = vi.fn().mockResolvedValue({
messageId: "$approval",
primaryMessageId: "$approval",
receipt: buildMatrixReceipt(["$approval"]),
roomId: "!room:example.org",
});
const reactMessage = vi.fn().mockResolvedValue(undefined);
const view = buildExecApprovalView();
const pendingPayload = await buildPendingPayload(view);
await matrixApprovalNativeRuntime.transport.deliverPending({
cfg: {} as never,
accountId: "default",
context: {
client: {} as never,
deps: {
sendSingleTextMessage,
reactMessage,
},
},
request: {} as never,
approvalKind: "exec",
plannedTarget: buildMatrixApprovalRoomTarget("!room:example.org"),
preparedTarget: {
to: "room:!room:example.org",
roomId: "!room:example.org",
},
view,
pendingPayload,
});
const [target, text, options] = mockCall(sendSingleTextMessage) ?? [];
expect(target).toBe("room:!room:example.org");
expect(String(text)).toContain("echo hi");
const extraContent = (options as { extraContent?: Record<string, unknown> } | undefined)
?.extraContent;
expectRecordFields(extraContent?.[MATRIX_APPROVAL_METADATA_KEY], {
version: 1,
type: "approval.request",
state: "pending",
id: "req-1",
kind: "exec",
commandText: "echo hi",
cwd: "/repo",
agentId: "agent-1",
allowedDecisions: ["allow-once", "deny"],
});
});
it("delivers Matrix approval content with plugin approval fields", async () => {
const sendSingleTextMessage = vi.fn().mockResolvedValue({
messageId: "$plugin-approval",
primaryMessageId: "$plugin-approval",
receipt: buildMatrixReceipt(["$plugin-approval"]),
roomId: "!room:example.org",
});
const reactMessage = vi.fn().mockResolvedValue(undefined);
const view = buildPluginApprovalView();
const pendingPayload = await buildPendingPayload(view);
await matrixApprovalNativeRuntime.transport.deliverPending({
cfg: {} as never,
accountId: "default",
context: {
client: {} as never,
deps: {
sendSingleTextMessage,
reactMessage,
},
},
request: {} as never,
approvalKind: "plugin",
plannedTarget: buildMatrixApprovalRoomTarget("!room:example.org"),
preparedTarget: {
to: "room:!room:example.org",
roomId: "!room:example.org",
},
view,
pendingPayload,
});
const [target, text, options] = mockCall(sendSingleTextMessage) ?? [];
expect(target).toBe("room:!room:example.org");
expect(String(text)).toContain("deploy");
const extraContent = (options as { extraContent?: Record<string, unknown> } | undefined)
?.extraContent;
expect(extraContent?.[MATRIX_APPROVAL_METADATA_KEY]).toEqual({
version: 1,
type: "approval.request",
state: "pending",
phase: "pending",
id: "plugin:req-1",
kind: "plugin",
title: "Plugin Approval Required",
description: "Approve the tool call.",
expiresAtMs: TEST_APPROVAL_EXPIRES_AT_MS,
metadata: [],
allowedDecisions: ["allow-once"],
actions: [
{
decision: "allow-once",
label: "Allow Once",
style: "success",
command: "/approve plugin:req-1 allow-once",
},
],
pluginId: "ops",
toolName: "deploy",
agentId: "agent-1",
severity: "critical",
});
expect(mockCall(reactMessage)?.[0]).toBe("!room:example.org");
expect(mockCall(reactMessage)?.[1]).toBe("$plugin-approval");
expect(mockCall(reactMessage)?.[2]).toBe("✅");
expectRecordFields(mockCall(reactMessage)?.[3], { accountId: "default" });
});
it("binds Matrix approval reactions before publishing option reactions", async () => {
const sendSingleTextMessage = vi.fn().mockResolvedValue({
messageId: "$approval",
primaryMessageId: "$approval",
receipt: buildMatrixReceipt(["$approval"]),
roomId: "!room:example.org",
});
const reactMessage = vi.fn().mockImplementation(async () => {
expect(
await resolveMatrixApprovalReactionTargetWithPersistence({
roomId: "!room:example.org",
eventId: "$approval",
reactionKey: "✅",
}),
).toEqual({
approvalId: "req-1",
approvalKind: "exec",
decision: "allow-once",
});
});
const view = buildExecApprovalView();
const pendingPayload = await buildPendingPayload(view);
await matrixApprovalNativeRuntime.transport.deliverPending({
cfg: {} as never,
accountId: "default",
context: {
client: {} as never,
deps: {
sendSingleTextMessage,
reactMessage,
},
},
request: {} as never,
approvalKind: "exec",
plannedTarget: buildMatrixApprovalRoomTarget("!room:example.org"),
preparedTarget: {
to: "room:!room:example.org",
roomId: "!room:example.org",
},
view,
pendingPayload,
});
expect(reactMessage).toHaveBeenCalled();
});
it("retries transient Matrix approval send failures", async () => {
const sendSingleTextMessage = vi
.fn()
.mockRejectedValueOnce(new Error("transient Matrix send failure"))
.mockResolvedValue({
messageId: "$approval",
primaryMessageId: "$approval",
receipt: buildMatrixReceipt(["$approval"]),
roomId: "!room:example.org",
});
const reactMessage = vi.fn().mockResolvedValue(undefined);
const view = buildExecApprovalView();
const pendingPayload = await buildPendingPayload(view);
const entry = await matrixApprovalNativeRuntime.transport.deliverPending({
cfg: {} as never,
accountId: "default",
context: {
client: {} as never,
deps: {
sendSingleTextMessage,
reactMessage,
},
},
request: {} as never,
approvalKind: "exec",
plannedTarget: buildMatrixApprovalRoomTarget("!room:example.org"),
preparedTarget: {
to: "room:!room:example.org",
roomId: "!room:example.org",
},
view,
pendingPayload,
});
expect(sendSingleTextMessage).toHaveBeenCalledTimes(2);
expectRecordFields(entry, {
roomId: "!room:example.org",
platformMessageIds: ["$approval"],
});
});
it("retries transient Matrix direct-room repair failures before preparing approval DMs", async () => {
const repairDirectRooms = vi
.fn()
.mockRejectedValueOnce(new Error("direct account data not ready"))
.mockResolvedValue({
activeRoomId: "!dm:example.org",
});
const prepared = await matrixApprovalNativeRuntime.transport.prepareTarget({
cfg: {
channels: {
matrix: {
encryption: false,
},
},
} as never,
accountId: "default",
context: {
client: {} as never,
deps: {
repairDirectRooms,
},
},
request: {} as never,
approvalKind: "exec",
view: buildExecApprovalView(),
pendingPayload: {} as never,
plannedTarget: {
surface: "approver-dm",
target: {
to: "user:@owner:example.org",
},
reason: "preferred",
},
});
expect(repairDirectRooms).toHaveBeenCalledTimes(2);
const preparedTarget = expectRecordFields(prepared, {});
expect(preparedTarget.target).toEqual({
to: "room:!dm:example.org",
roomId: "!dm:example.org",
threadId: undefined,
});
});
it("falls back to chunked Matrix delivery when approval content exceeds one event", async () => {
const sendSingleTextMessage = vi
.fn()
.mockRejectedValue(new Error("Matrix single-message text exceeds limit (5000 > 4000)"));
const sendMessage = vi.fn().mockResolvedValue({
messageId: "$last",
primaryMessageId: "$legacy-primary",
receipt: buildMatrixReceipt(["$primary", "$last"]),
roomId: "!room:example.org",
});
const reactMessage = vi.fn().mockResolvedValue(undefined);
const view = buildExecApprovalView({
actions: [
{
decision: "allow-once",
label: "Allow Once",
style: "success",
command: "/approve req-1 allow-once",
},
],
});
const pendingPayload = await buildPendingPayload(view);
const entry = await matrixApprovalNativeRuntime.transport.deliverPending({
cfg: {} as never,
accountId: "default",
context: {
client: {} as never,
deps: {
sendSingleTextMessage,
sendMessage,
reactMessage,
},
},
request: {} as never,
approvalKind: "exec",
plannedTarget: buildMatrixApprovalRoomTarget("!room:example.org"),
preparedTarget: {
to: "room:!room:example.org",
roomId: "!room:example.org",
},
view,
pendingPayload,
});
expect(mockCall(sendMessage)?.[0]).toBe("room:!room:example.org");
expect(mockCall(sendMessage)?.[1]).toBe(pendingPayload.text);
expectRecordFields(mockCall(sendMessage)?.[2], {
accountId: "default",
extraContent: pendingPayload.extraContent,
});
expect(mockCall(reactMessage)?.[0]).toBe("!room:example.org");
expect(mockCall(reactMessage)?.[1]).toBe("$primary");
expect(typeof mockCall(reactMessage)?.[2]).toBe("string");
expectRecordFields(mockCall(reactMessage)?.[3], { accountId: "default" });
expectRecordFields(entry, {
roomId: "!room:example.org",
platformMessageIds: ["$primary", "$last"],
reactionEventId: "$primary",
});
const bindPending = matrixApprovalNativeRuntime.interactions?.bindPending;
if (!bindPending) {
throw new Error("Matrix approval runtime must expose bindPending");
}
const binding = await bindPending({
cfg: {} as never,
accountId: "default",
context: {
client: {} as never,
},
request: {} as never,
approvalKind: "exec",
view,
pendingPayload,
entry: entry!,
});
expect(binding).toEqual({
accountId: "default",
roomId: "!room:example.org",
eventId: "$primary",
});
expect(
await resolveMatrixApprovalReactionTargetWithPersistence({
roomId: "!room:example.org",
eventId: "$primary",
reactionKey: "✅",
}),
).toEqual({
approvalId: "req-1",
approvalKind: "exec",
decision: "allow-once",
});
expect(
await resolveMatrixApprovalReactionTargetWithPersistence({
roomId: "!room:example.org",
eventId: "$last",
reactionKey: "✅",
}),
).toBeNull();
});
it("uses a longer code fence when resolved commands contain triple backticks", async () => {
const result = await matrixApprovalNativeRuntime.presentation.buildResolvedResult({
cfg: {} as never,
accountId: "default",
context: {
client: {} as never,
},
request: {
id: "req-1",
request: {
command: "echo hi",
},
createdAtMs: 0,
expiresAtMs: 1_000,
},
resolved: {
id: "req-1",
decision: "allow-once",
ts: 0,
},
view: {
approvalKind: "exec",
approvalId: "req-1",
decision: "allow-once",
commandText: "echo ```danger```",
} as never,
entry: {} as never,
});
expect(result).toEqual({
kind: "update",
payload: [
"Exec approval: Allowed once",
"",
"Command",
"````",
"echo ```danger```",
"````",
].join("\n"),
});
});
});