Skip to content

Commit fde7a61

Browse files
author
Peter Steinberger
committed
fix(imessage): settle native inbound reply delivery
1 parent ee320a6 commit fde7a61

4 files changed

Lines changed: 432 additions & 68 deletions

File tree

‎extensions/imessage/src/monitor.plugin-payload.test.ts‎

Lines changed: 189 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,30 @@
11
// Imessage tests cover monitor.plugin payload plugin behavior.
2+
import path from "node:path";
3+
import * as channelInbound from "openclaw/plugin-sdk/channel-inbound";
4+
import {
5+
addTestHook,
6+
createEmptyPluginRegistry,
7+
createTestInboundDebounceFlush,
8+
initializeGlobalHookRunner,
9+
resetGlobalHookRunner,
10+
} from "openclaw/plugin-sdk/channel-test-helpers";
11+
import { recordInboundSession } from "openclaw/plugin-sdk/conversation-runtime";
12+
import type { dispatchReplyWithBufferedBlockDispatcher } from "openclaw/plugin-sdk/reply-runtime";
13+
import { resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
214
import type { waitForTransportReady } from "openclaw/plugin-sdk/transport-ready-runtime";
3-
import { beforeEach, describe, expect, it, vi } from "vitest";
15+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
416
import type { createIMessageRpcClient } from "./client.js";
517
import { monitorIMessageProvider } from "./monitor.js";
18+
import { setCachedIMessagePrivateApiStatus } from "./private-api-status.js";
19+
import { getIMessageRuntime } from "./runtime.js";
620
import { installIMessageStateRuntimeForTest } from "./test-support/runtime.js";
721

822
const waitForTransportReadyMock = vi.hoisted(() =>
923
vi.fn<typeof waitForTransportReady>(async () => {}),
1024
);
1125
const createIMessageRpcClientMock = vi.hoisted(() => vi.fn<typeof createIMessageRpcClient>());
1226
const shouldDebounceTextInboundMock = vi.hoisted(() => vi.fn(() => false));
27+
const directDeliveryProof = vi.hoisted(() => ({ flush: false }));
1328

1429
vi.mock("openclaw/plugin-sdk/transport-ready-runtime", () => ({
1530
waitForTransportReady: waitForTransportReadyMock,
@@ -20,10 +35,19 @@ vi.mock("openclaw/plugin-sdk/channel-inbound", async (importOriginal) => {
2035
return {
2136
...actual,
2237
createChannelInboundDebouncer: vi.fn(
23-
(opts: { shouldDebounce: (entry: unknown) => boolean }) => ({
38+
(opts: {
39+
shouldDebounce: (entry: unknown) => boolean;
40+
onFlush: (
41+
entries: unknown[],
42+
createFlush: typeof createTestInboundDebounceFlush,
43+
) => { completion: Promise<void> };
44+
}) => ({
2445
debouncer: {
2546
enqueue: async (entry: unknown) => {
2647
opts.shouldDebounce(entry);
48+
if (directDeliveryProof.flush) {
49+
await opts.onFlush([entry], createTestInboundDebounceFlush).completion;
50+
}
2751
},
2852
},
2953
}),
@@ -46,6 +70,12 @@ describe("iMessage plugin payload attachments", () => {
4670
waitForTransportReadyMock.mockReset().mockResolvedValue(undefined);
4771
createIMessageRpcClientMock.mockReset();
4872
shouldDebounceTextInboundMock.mockReset().mockReturnValue(false);
73+
directDeliveryProof.flush = false;
74+
});
75+
76+
afterEach(() => {
77+
resetGlobalHookRunner();
78+
vi.restoreAllMocks();
4979
});
5080

5181
it("does not count Apple rich-link plugin payloads as user media", async () => {
@@ -103,4 +133,161 @@ describe("iMessage plugin payload attachments", () => {
103133
}),
104134
);
105135
});
136+
137+
it.each([
138+
{ kind: "tool", text: "provider-visible tool result", visible: true },
139+
{ kind: "block", text: "provider-visible streamed block", visible: true },
140+
{ kind: "tool", text: "<thinking>private reasoning</thinking>", visible: false },
141+
] as const)(
142+
"settles direct $kind delivery through actual provider, hooks, and SQLite ($visible)",
143+
async ({ kind, text, visible }) => {
144+
directDeliveryProof.flush = true;
145+
const messageSent = vi.fn();
146+
const registry = createEmptyPluginRegistry();
147+
addTestHook({
148+
registry,
149+
pluginId: "imessage-monitor-proof",
150+
hookName: "message_sent",
151+
handler: messageSent,
152+
});
153+
initializeGlobalHookRunner(registry);
154+
setCachedIMessagePrivateApiStatus("imsg", {
155+
available: true,
156+
v2Ready: true,
157+
selectors: {},
158+
rpcMethods: ["watch.subscribe", "send"],
159+
});
160+
161+
const dispatch = vi.fn<typeof dispatchReplyWithBufferedBlockDispatcher>(async (params) => {
162+
const settled = await params.dispatcherOptions.deliver({ text }, { kind });
163+
expect(settled).toMatchObject(
164+
visible
165+
? {
166+
visibleReplySent: true,
167+
messageIds: [`native-${kind}-guid`],
168+
receipt: { platformMessageIds: [`native-${kind}-guid`] },
169+
content: text,
170+
}
171+
: { visibleReplySent: false, suppression: { reason: "no_visible_result" } },
172+
);
173+
return {
174+
queuedFinal: false,
175+
counts: { tool: kind === "tool" ? 1 : 0, block: kind === "block" ? 1 : 0, final: 0 },
176+
};
177+
});
178+
const runActual = channelInbound.runChannelInboundEvent;
179+
vi.spyOn(channelInbound, "runChannelInboundEvent").mockImplementation(async (params) =>
180+
runActual({
181+
...params,
182+
adapter: {
183+
...params.adapter,
184+
resolveTurn: async (input, eventClass, preflight) => {
185+
const turn = await params.adapter.resolveTurn(input, eventClass, preflight);
186+
if (!("route" in turn) || !("delivery" in turn)) {
187+
throw new Error("expected assembled iMessage delivery turn");
188+
}
189+
const { route, ...resolvedTurn } = turn;
190+
return {
191+
...resolvedTurn,
192+
agentId: route.agentId,
193+
routeSessionKey: route.sessionKey,
194+
storePath: resolveStorePath(turn.cfg.session?.store, { agentId: route.agentId }),
195+
recordInboundSession,
196+
dispatchReplyWithBufferedBlockDispatcher: dispatch,
197+
};
198+
},
199+
},
200+
}),
201+
);
202+
203+
const nativeClient = {
204+
request: vi.fn(async (method: string) => {
205+
if (method !== "send") {
206+
throw new Error(`unexpected native iMessage method ${method}`);
207+
}
208+
return { guid: `native-${kind}-guid`, status: "sent" };
209+
}),
210+
stop: vi.fn(async () => {}),
211+
};
212+
let onNotification: ((message: { method: string; params: unknown }) => void) | undefined;
213+
const watchClient = {
214+
request: vi.fn(async () => ({ subscription: 1 })),
215+
waitForClose: vi.fn(async () => {
216+
onNotification?.({
217+
method: "message",
218+
params: {
219+
message: {
220+
id: 91,
221+
guid: `monitor-${kind}-${visible}-guid`,
222+
chat_id: 123,
223+
sender: "+15550001111",
224+
is_from_me: false,
225+
text: "exercise actual direct delivery",
226+
is_group: false,
227+
created_at: new Date().toISOString(),
228+
},
229+
},
230+
});
231+
await Promise.resolve();
232+
await Promise.resolve();
233+
}),
234+
stop: vi.fn(async () => {}),
235+
};
236+
createIMessageRpcClientMock.mockImplementation(async (params) => {
237+
if (params?.onNotification) {
238+
onNotification = params.onNotification;
239+
return watchClient as never;
240+
}
241+
return nativeClient as never;
242+
});
243+
244+
await monitorIMessageProvider({
245+
config: {
246+
channels: {
247+
imessage: {
248+
dmPolicy: "allowlist",
249+
allowFrom: ["+15550001111"],
250+
sendReadReceipts: false,
251+
},
252+
},
253+
messages: { inbound: { debounceMs: 0 } },
254+
session: { mainKey: "main" },
255+
} as never,
256+
runtime: { error: vi.fn(), exit: vi.fn(), log: vi.fn() },
257+
});
258+
259+
if (!visible) {
260+
expect(nativeClient.request).not.toHaveBeenCalled();
261+
expect(messageSent).not.toHaveBeenCalled();
262+
return;
263+
}
264+
await vi.waitFor(() => {
265+
expect(messageSent).toHaveBeenCalledOnce();
266+
});
267+
expect(messageSent).toHaveBeenCalledWith(
268+
expect.objectContaining({ content: text, success: true, messageId: `native-${kind}-guid` }),
269+
expect.objectContaining({ channelId: "imessage" }),
270+
);
271+
272+
const { DatabaseSync } = await import("node:sqlite");
273+
const database = new DatabaseSync(
274+
path.join(getIMessageRuntime().state.resolveStateDir(), "state", "openclaw.sqlite"),
275+
{ readOnly: true },
276+
);
277+
try {
278+
const persisted = database
279+
.prepare(
280+
"SELECT value_json FROM plugin_state_entries WHERE plugin_id = ? AND namespace = ?",
281+
)
282+
.all("imessage", "imessage.sent-echoes");
283+
expect(persisted).toEqual(
284+
expect.arrayContaining([
285+
expect.objectContaining({ value_json: expect.stringContaining(`native-${kind}-guid`) }),
286+
]),
287+
);
288+
} finally {
289+
database.close();
290+
}
291+
},
292+
);
106293
});

0 commit comments

Comments
 (0)