Files
adolf/extensions/imessage/src/approval-reaction-poller.test.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

616 lines
20 KiB
TypeScript

// Imessage tests cover approval reaction poller plugin behavior.
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
clearIMessageApprovalReactionPollerStateForTest,
pollPendingIMessageApprovalReactions,
} from "./approval-reaction-poller.js";
import {
clearIMessageApprovalReactionTargetsForTest,
registerIMessageApprovalReactionTarget,
} from "./approval-reactions.js";
import type { IMessageRpcClient } from "./client.js";
const resolverMocks = vi.hoisted(() => ({
resolveIMessageApproval: vi.fn(),
isApprovalNotFoundError: vi.fn(() => false),
}));
vi.mock("./approval-resolver.js", () => ({
resolveIMessageApproval: resolverMocks.resolveIMessageApproval,
isApprovalNotFoundError: resolverMocks.isApprovalNotFoundError,
}));
function createClient(request: ReturnType<typeof vi.fn>): IMessageRpcClient {
return { request } as unknown as IMessageRpcClient;
}
describe("iMessage approval reaction poller", () => {
beforeEach(() => {
clearIMessageApprovalReactionTargetsForTest();
clearIMessageApprovalReactionPollerStateForTest();
resolverMocks.resolveIMessageApproval.mockReset();
resolverMocks.resolveIMessageApproval.mockResolvedValue(undefined);
resolverMocks.isApprovalNotFoundError.mockReset();
resolverMocks.isApprovalNotFoundError.mockReturnValue(false);
});
it("does not scan recent chats during fast polling with no pending targets", async () => {
const request = vi.fn();
await pollPendingIMessageApprovalReactions({
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
});
expect(request).not.toHaveBeenCalled();
});
it("does not scan recent chats during fast polling for handle-only targets", async () => {
registerIMessageApprovalReactionTarget({
accountId: "default",
conversation: { handle: "+15551230000" },
messageId: "msg-1",
approvalId: "exec-1",
allowedDecisions: ["allow-once", "deny"],
});
const request = vi.fn();
await pollPendingIMessageApprovalReactions({
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
});
expect(request).not.toHaveBeenCalled();
});
it("discovers observed approval prompts on the bounded recent-chat path", async () => {
const request = vi.fn(async (method: string) => {
if (method === "chats.list") {
return { chats: [{ id: 42 }] };
}
if (method === "messages.history") {
return {
messages: [
{
guid: "msg-1",
chat_id: 42,
chat_guid: "SMS;-;+15551230000",
chat_identifier: "+15551230000",
is_from_me: true,
sender: "+15551230000",
text: [
"Exec approval required",
"ID: exec-1",
"",
"Reply with: /approve exec-1 allow-once|deny",
].join("\n"),
reactions: [
{
id: 7,
sender: "+15551230000",
is_from_me: true,
type: "like",
emoji: "👍",
created_at: "2026-05-27T21:00:00.000Z",
},
],
},
],
};
}
throw new Error(`unexpected method ${method}`);
});
await pollPendingIMessageApprovalReactions({
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
allowRecentChatDiscovery: true,
});
expect(request).toHaveBeenCalledWith("chats.list", { limit: 50 }, { timeoutMs: 10_000 });
expect(resolverMocks.resolveIMessageApproval).toHaveBeenCalledWith({
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
approvalId: "exec-1",
decision: "allow-once",
senderId: "+15551230000",
gatewayUrl: undefined,
});
});
it("bounds no-target recent-chat discovery to one pass per account", async () => {
const request = vi.fn(async (method: string) => {
if (method === "chats.list") {
return { chats: [{ id: 42 }] };
}
if (method === "messages.history") {
return { messages: [] };
}
throw new Error(`unexpected method ${method}`);
});
const pollParams = {
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
allowRecentChatDiscovery: true,
};
await pollPendingIMessageApprovalReactions(pollParams);
await pollPendingIMessageApprovalReactions(pollParams);
expect(request).toHaveBeenCalledTimes(2);
expect(request).toHaveBeenCalledWith("chats.list", { limit: 50 }, { timeoutMs: 10_000 });
expect(request).toHaveBeenCalledWith(
"messages.history",
{ chat_id: 42, limit: 30 },
{ timeoutMs: 10_000 },
);
});
it("bounds no-target discovery after resolving an observed reaction", async () => {
const request = vi.fn(async (method: string, payload?: { chat_id?: number }) => {
if (method === "chats.list") {
return { chats: [{ id: 42 }, { id: 99 }] };
}
if (method === "messages.history" && payload?.chat_id === 42) {
return {
messages: [
{
guid: "msg-1",
chat_id: 42,
chat_guid: "SMS;-;+15551230000",
chat_identifier: "+15551230000",
is_from_me: true,
sender: "+15551230000",
text: [
"Exec approval required",
"ID: exec-1",
"",
"Reply with: /approve exec-1 allow-once|deny",
].join("\n"),
reactions: [
{
id: 7,
sender: "+15551230000",
is_from_me: true,
type: "like",
emoji: "👍",
created_at: "2026-05-27T21:00:00.000Z",
},
],
},
],
};
}
if (method === "messages.history" && payload?.chat_id === 99) {
return { messages: [] };
}
throw new Error(`unexpected request ${method} ${JSON.stringify(payload)}`);
});
const pollParams = {
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
allowRecentChatDiscovery: true,
};
await pollPendingIMessageApprovalReactions(pollParams);
await pollPendingIMessageApprovalReactions(pollParams);
expect(resolverMocks.resolveIMessageApproval).toHaveBeenCalledTimes(1);
expect(request.mock.calls.filter(([method]) => method === "chats.list")).toHaveLength(1);
expect(request.mock.calls.filter(([method]) => method === "messages.history")).toHaveLength(2);
expect(request).toHaveBeenCalledWith(
"messages.history",
{ chat_id: 99, limit: 30 },
{ timeoutMs: 10_000 },
);
});
it("retries no-target discovery after resolver failures expire observed targets", async () => {
resolverMocks.resolveIMessageApproval.mockRejectedValue(new Error("gateway down"));
const request = vi.fn(async (method: string) => {
if (method === "chats.list") {
return { chats: [{ id: 42 }] };
}
if (method === "messages.history") {
return {
messages: [
{
guid: "msg-1",
chat_id: 42,
chat_guid: "SMS;-;+15551230000",
chat_identifier: "+15551230000",
is_from_me: true,
sender: "+15551230000",
text: [
"Exec approval required",
"ID: exec-1",
"",
"Reply with: /approve exec-1 allow-once|deny",
].join("\n"),
reactions: [
{
id: 7,
sender: "+15551230000",
is_from_me: true,
type: "like",
emoji: "👍",
created_at: "2026-05-27T21:00:00.000Z",
},
],
},
],
};
}
throw new Error(`unexpected method ${method}`);
});
const dateNow = vi.spyOn(Date, "now").mockReturnValue(1_800_000_000_000);
try {
const pollParams = {
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
allowRecentChatDiscovery: true,
};
await pollPendingIMessageApprovalReactions(pollParams);
dateNow.mockReturnValue(1_800_000_301_000);
await pollPendingIMessageApprovalReactions(pollParams);
} finally {
dateNow.mockRestore();
}
expect(resolverMocks.resolveIMessageApproval).toHaveBeenCalledTimes(2);
expect(request.mock.calls.filter(([method]) => method === "chats.list")).toHaveLength(2);
});
it("retries no-target recent-chat discovery after the first chat list fails", async () => {
const request = vi.fn(async (method: string) => {
if (method === "chats.list") {
const chatListCalls = request.mock.calls.filter(
([calledMethod]) => calledMethod === "chats.list",
);
if (chatListCalls.length === 1) {
throw new Error("temporary imsg failure");
}
return { chats: [{ id: 42 }] };
}
if (method === "messages.history") {
return { messages: [] };
}
throw new Error(`unexpected method ${method}`);
});
const pollParams = {
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
allowRecentChatDiscovery: true,
};
await expect(pollPendingIMessageApprovalReactions(pollParams)).rejects.toThrow(
"temporary imsg failure",
);
await pollPendingIMessageApprovalReactions(pollParams);
expect(request.mock.calls.filter(([method]) => method === "chats.list")).toHaveLength(2);
expect(request.mock.calls.filter(([method]) => method === "messages.history")).toHaveLength(1);
});
it("retries no-target recent-chat discovery after the first history fetch fails", async () => {
const request = vi.fn(async (method: string) => {
if (method === "chats.list") {
return { chats: [{ id: 42 }] };
}
if (method === "messages.history") {
const historyCalls = request.mock.calls.filter(
([calledMethod]) => calledMethod === "messages.history",
);
if (historyCalls.length === 1) {
throw new Error("temporary history failure");
}
return { messages: [] };
}
throw new Error(`unexpected method ${method}`);
});
const pollParams = {
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
allowRecentChatDiscovery: true,
};
await pollPendingIMessageApprovalReactions(pollParams);
await pollPendingIMessageApprovalReactions(pollParams);
await pollPendingIMessageApprovalReactions(pollParams);
expect(request.mock.calls.filter(([method]) => method === "chats.list")).toHaveLength(2);
expect(request.mock.calls.filter(([method]) => method === "messages.history")).toHaveLength(2);
});
it("does not bind observed approval prompts when the process clock is invalid", async () => {
const request = vi.fn(async (method: string) => {
if (method === "chats.list") {
return { chats: [{ id: 42 }] };
}
if (method === "messages.history") {
return {
messages: [
{
guid: "msg-1",
chat_id: 42,
chat_guid: "SMS;-;+15551230000",
chat_identifier: "+15551230000",
is_from_me: true,
sender: "+15551230000",
text: "Exec approval required\nID: exec-1",
reactions: [
{
id: 7,
sender: "+15551230000",
is_from_me: true,
type: "like",
emoji: "👍",
created_at: "2026-05-27T21:00:00.000Z",
},
],
},
],
};
}
throw new Error(`unexpected method ${method}`);
});
const dateNow = vi.spyOn(Date, "now").mockReturnValue(Number.NaN);
try {
await pollPendingIMessageApprovalReactions({
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
allowRecentChatDiscovery: true,
});
} finally {
dateNow.mockRestore();
}
expect(resolverMocks.resolveIMessageApproval).not.toHaveBeenCalled();
});
it("uses learned chat ids for fast scoped polling after discovery", async () => {
registerIMessageApprovalReactionTarget({
accountId: "default",
conversation: { handle: "+15551230000" },
messageId: "msg-1",
approvalId: "exec-1",
allowedDecisions: ["allow-once", "deny"],
});
registerIMessageApprovalReactionTarget({
accountId: "default",
conversation: { chatId: 42, chatGuid: "SMS;-;+15551230000" },
messageId: "msg-1",
approvalId: "exec-1",
allowedDecisions: ["allow-once", "deny"],
});
const request = vi.fn(async (method: string) => {
if (method === "messages.history") {
return { messages: [] };
}
throw new Error(`unexpected method ${method}`);
});
await pollPendingIMessageApprovalReactions({
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
});
expect(request).toHaveBeenCalledTimes(1);
expect(request).toHaveBeenCalledWith(
"messages.history",
{ chat_id: 42, limit: 30 },
{ timeoutMs: 10_000 },
);
});
it("includes recent chats during discovery when scoped and unscoped targets are pending", async () => {
registerIMessageApprovalReactionTarget({
accountId: "default",
conversation: { chatId: 42, chatGuid: "SMS;-;+15551230000" },
messageId: "msg-scoped",
approvalId: "exec-scoped",
allowedDecisions: ["allow-once", "deny"],
});
registerIMessageApprovalReactionTarget({
accountId: "default",
conversation: { handle: "+15551239999" },
messageId: "msg-handle",
approvalId: "exec-handle",
allowedDecisions: ["allow-once", "deny"],
});
const request = vi.fn(async (method: string, payload?: { chat_id?: number }) => {
if (method === "chats.list") {
return { chats: [{ id: 42 }, { id: 99 }] };
}
if (method === "messages.history" && payload?.chat_id === 42) {
return { messages: [] };
}
if (method === "messages.history" && payload?.chat_id === 99) {
return {
messages: [
{
guid: "msg-handle",
chat_id: 99,
chat_guid: "SMS;-;+15551239999",
chat_identifier: "+15551239999",
is_from_me: true,
sender: "+15551239999",
text: "Exec approval required\nID: exec-handle",
reactions: [
{
id: 8,
sender: "+15551239999",
is_from_me: true,
type: "like",
emoji: "👍",
created_at: "2026-05-27T21:01:00.000Z",
},
],
},
],
};
}
throw new Error(`unexpected request ${method} ${JSON.stringify(payload)}`);
});
await pollPendingIMessageApprovalReactions({
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551239999"] } } },
accountId: "default",
allowRecentChatDiscovery: true,
});
expect(request).toHaveBeenCalledWith("chats.list", { limit: 50 }, { timeoutMs: 10_000 });
expect(request).toHaveBeenCalledWith(
"messages.history",
{ chat_id: 42, limit: 30 },
{ timeoutMs: 10_000 },
);
expect(request).toHaveBeenCalledWith(
"messages.history",
{ chat_id: 99, limit: 30 },
{ timeoutMs: 10_000 },
);
expect(resolverMocks.resolveIMessageApproval).toHaveBeenCalledWith({
cfg: { channels: { imessage: { allowFrom: ["+15551239999"] } } },
approvalId: "exec-handle",
decision: "allow-once",
senderId: "+15551239999",
gatewayUrl: undefined,
});
});
it("continues scanning after an unauthorized reaction leaves the approval pending", async () => {
registerIMessageApprovalReactionTarget({
accountId: "default",
conversation: { chatId: 42, chatGuid: "iMessage;+;chat-guid" },
messageId: "msg-1",
approvalId: "exec-1",
allowedDecisions: ["allow-once", "deny"],
});
const request = vi.fn(async (method: string) => {
if (method === "messages.history") {
return {
messages: [
{
guid: "msg-1",
chat_id: 42,
chat_guid: "iMessage;+;chat-guid",
is_group: true,
is_from_me: true,
text: "Exec approval required\nID: exec-1",
reactions: [
{
id: 8,
sender: "+15550000000",
type: "like",
emoji: "👍",
created_at: "2026-05-27T21:01:00.000Z",
},
{
id: 9,
sender: "+15551230000",
type: "like",
emoji: "👍",
created_at: "2026-05-27T21:02:00.000Z",
},
],
},
],
};
}
throw new Error(`unexpected method ${method}`);
});
await pollPendingIMessageApprovalReactions({
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
});
expect(resolverMocks.resolveIMessageApproval).toHaveBeenCalledTimes(1);
expect(resolverMocks.resolveIMessageApproval).toHaveBeenCalledWith({
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
approvalId: "exec-1",
decision: "allow-once",
senderId: "+15551230000",
gatewayUrl: undefined,
});
});
it("stops scanning after an authorized resolver failure", async () => {
resolverMocks.resolveIMessageApproval.mockRejectedValueOnce(new Error("gateway down"));
registerIMessageApprovalReactionTarget({
accountId: "default",
conversation: { chatId: 42, chatGuid: "iMessage;+;chat-guid" },
messageId: "msg-1",
approvalId: "exec-1",
allowedDecisions: ["allow-once", "deny"],
});
const request = vi.fn(async (method: string) => {
if (method === "messages.history") {
return {
messages: [
{
guid: "msg-1",
chat_id: 42,
chat_guid: "iMessage;+;chat-guid",
is_group: true,
is_from_me: true,
text: "Exec approval required\nID: exec-1",
reactions: [
{
id: 8,
sender: "+15551230000",
type: "like",
emoji: "👍",
created_at: "2026-05-27T21:01:00.000Z",
},
{
id: 9,
sender: "+15551230000",
type: "dislike",
emoji: "👎",
created_at: "2026-05-27T21:02:00.000Z",
},
],
},
],
};
}
throw new Error(`unexpected method ${method}`);
});
await pollPendingIMessageApprovalReactions({
client: createClient(request),
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
accountId: "default",
});
expect(resolverMocks.resolveIMessageApproval).toHaveBeenCalledTimes(1);
expect(resolverMocks.resolveIMessageApproval).toHaveBeenCalledWith({
cfg: { channels: { imessage: { allowFrom: ["+15551230000"] } } },
approvalId: "exec-1",
decision: "allow-once",
senderId: "+15551230000",
gatewayUrl: undefined,
});
});
});