Skip to content

Commit ee320a6

Browse files
steipetePeter Steinberger
andauthored
fix(imessage): preserve outbound attachment delivery facts (#117238)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 51c41c2 commit ee320a6

6 files changed

Lines changed: 485 additions & 26 deletions

File tree

‎extensions/imessage/src/channel.runtime.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,4 +145,40 @@ describe("sendIMessageOutbound approval identity", () => {
145145
expect.objectContaining({ conversationReadOrigin: "delegated" }),
146146
);
147147
});
148+
149+
it("forwards accepted attachment progress before a later native caption failure", async () => {
150+
const receipt = {
151+
primaryPlatformMessageId: "p:0/accepted-attachment",
152+
platformMessageIds: ["p:0/accepted-attachment"],
153+
parts: [{ platformMessageId: "p:0/accepted-attachment", kind: "media" as const, index: 0 }],
154+
sentAt: 1_000,
155+
};
156+
const accepted = {
157+
content: "",
158+
messageId: "p:0/accepted-attachment",
159+
messageIds: ["p:0/accepted-attachment"],
160+
sentText: "",
161+
receipt,
162+
visibleReplySent: true as const,
163+
};
164+
const captionError = new Error("caption failed after accepted attachment");
165+
const send = vi.fn(async (_to, _text, options) => {
166+
await options.onDeliveryResult?.(accepted);
167+
throw captionError;
168+
});
169+
const onDeliveryResult = vi.fn();
170+
171+
await expect(
172+
sendIMessageOutbound({
173+
cfg: {} as never,
174+
to: "+15551230000",
175+
text: "caption",
176+
mediaUrl: "/tmp/report.pdf",
177+
deps: { imessage: send },
178+
onDeliveryResult,
179+
}),
180+
).rejects.toBe(captionError);
181+
182+
expect(onDeliveryResult).toHaveBeenCalledExactlyOnceWith(accepted);
183+
});
148184
});

‎extensions/imessage/src/channel.runtime.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export async function sendIMessageOutbound(params: {
2222
deps?: { [channelId: string]: unknown };
2323
replyToId?: string;
2424
conversationReadOrigin?: "delegated" | "direct-operator";
25+
onDeliveryResult?: NonNullable<Parameters<IMessageSendFn>[2]["onDeliveryResult"]>;
2526
}) {
2627
const send =
2728
resolveOutboundSendDep<IMessageSendFn>(params.deps, "imessage", {
@@ -43,6 +44,7 @@ export async function sendIMessageOutbound(params: {
4344
accountId: params.accountId ?? undefined,
4445
replyToId: params.replyToId ?? undefined,
4546
conversationReadOrigin: params.conversationReadOrigin,
47+
...(params.onDeliveryResult ? { onDeliveryResult: params.onDeliveryResult } : {}),
4648
});
4749
const meta = {
4850
...(result as typeof result & { meta?: Record<string, unknown> }).meta,

‎extensions/imessage/src/channel.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,19 @@ const imessageMessageAdapter = defineChannelMessageAdapter({
173173
replyToId: ctx.replyToId ?? undefined,
174174
conversationReadOrigin: (ctx as typeof ctx & IMessageMessageContextExtras)
175175
.conversationReadOrigin,
176+
...(ctx.onDeliveryResult
177+
? {
178+
onDeliveryResult: async (acceptedResult) => {
179+
await ctx.onDeliveryResult?.(
180+
toIMessageMessageSendResult(
181+
acceptedResult,
182+
ctx.audioAsVoice ? "voice" : "media",
183+
ctx.replyToId,
184+
),
185+
);
186+
},
187+
}
188+
: {}),
176189
});
177190
return toIMessageMessageSendResult(
178191
result,
@@ -457,6 +470,7 @@ export const imessagePlugin: ChannelPlugin<ResolvedIMessageAccount, IMessageProb
457470
accountId,
458471
deps,
459472
replyToId,
473+
onDeliveryResult,
460474
}) =>
461475
await (
462476
await loadIMessageChannelRuntime()
@@ -470,6 +484,21 @@ export const imessagePlugin: ChannelPlugin<ResolvedIMessageAccount, IMessageProb
470484
accountId: accountId ?? undefined,
471485
deps,
472486
replyToId: replyToId ?? undefined,
487+
...(onDeliveryResult
488+
? {
489+
onDeliveryResult: async (result) => {
490+
await onDeliveryResult({
491+
channel: "imessage",
492+
...toIMessageMessageSendResult(
493+
result,
494+
audioAsVoice ? "voice" : "media",
495+
replyToId,
496+
),
497+
messageId: result.messageId,
498+
});
499+
},
500+
}
501+
: {}),
473502
}),
474503
},
475504
},

‎extensions/imessage/src/send.test.ts‎

Lines changed: 184 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import fs from "node:fs";
33
import os from "node:os";
44
import path from "node:path";
5+
import { isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
56
import { createOpenClawTestState, type OpenClawTestState } from "openclaw/plugin-sdk/test-state";
67
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
78
import type { IMessageRpcClient } from "./client.js";
@@ -94,6 +95,12 @@ describe("sendMessageIMessage receipts", () => {
9495
await openClawState.cleanup();
9596
});
9697

98+
function createOutboundMediaFile(filename: string, contents: Buffer): string {
99+
const sourcePath = openClawState.path(filename);
100+
fs.writeFileSync(sourcePath, contents);
101+
return sourcePath;
102+
}
103+
97104
it("attaches a text receipt for native send ids", async () => {
98105
const client = createClient({ guid: "p:0/imsg-1" });
99106

@@ -560,6 +567,71 @@ describe("sendMessageIMessage receipts", () => {
560567
expect(result.receipt.sentAt).toBeGreaterThan(0);
561568
});
562569

570+
it.each([
571+
{ kind: "document", filename: "quarterly-report.pdf", audioAsVoice: false },
572+
{ kind: "voice", filename: "spoken-reply.mp3", audioAsVoice: true },
573+
] as const)(
574+
"preserves the original $kind filename through the real media store and native CLI provider",
575+
async ({ filename, audioAsVoice }) => {
576+
const attachmentBytes = Buffer.from(`actual-provider-attachment-${filename}`);
577+
const sourcePath = createOutboundMediaFile(filename, attachmentBytes);
578+
const deliveredPaths: string[] = [];
579+
const runCliJson = vi.fn(async (args: readonly string[]) => {
580+
const attachmentPath = args[args.indexOf("--file") + 1];
581+
expect(attachmentPath).toBeDefined();
582+
deliveredPaths.push(attachmentPath!);
583+
expect(fs.readFileSync(attachmentPath!)).toEqual(attachmentBytes);
584+
return { messageId: "p:0/provider-accepted-media" };
585+
});
586+
587+
await sendMessageIMessage("chat_guid:chat-1", "", {
588+
config: IMESSAGE_TEST_CFG,
589+
mediaUrl: sourcePath,
590+
mediaLocalRoots: [openClawState.root],
591+
audioAsVoice,
592+
runCliJson,
593+
});
594+
595+
expect(deliveredPaths.map((attachmentPath) => path.basename(attachmentPath))).toEqual([
596+
filename,
597+
]);
598+
expect(fs.existsSync(deliveredPaths[0]!)).toBe(false);
599+
const storedFilenames = fs.readdirSync(openClawState.statePath("media", "outbound"));
600+
expect(storedFilenames).toHaveLength(1);
601+
expect(storedFilenames[0]).toMatch(/---[a-f\d-]{36}\./iu);
602+
expect(
603+
fs.readFileSync(openClawState.statePath("media", "outbound", storedFilenames[0]!)),
604+
).toEqual(attachmentBytes);
605+
expect(fs.existsSync(sourcePath)).toBe(true);
606+
},
607+
);
608+
609+
it("cleans an original-name CLI attachment workspace when the native provider rejects it", async () => {
610+
const filename = "rejected-report.pdf";
611+
const sourcePath = createOutboundMediaFile(filename, Buffer.from("provider rejection bytes"));
612+
let deliveredPath: string | undefined;
613+
const providerError = new Error("native attachment rejected");
614+
const runCliJson = vi.fn(async (args: readonly string[]) => {
615+
deliveredPath = args[args.indexOf("--file") + 1];
616+
expect(path.basename(deliveredPath!)).toBe(filename);
617+
expect(fs.existsSync(deliveredPath!)).toBe(true);
618+
throw providerError;
619+
});
620+
621+
await expect(
622+
sendMessageIMessage("chat_guid:chat-1", "", {
623+
config: IMESSAGE_TEST_CFG,
624+
mediaUrl: sourcePath,
625+
mediaLocalRoots: [openClawState.root],
626+
runCliJson,
627+
}),
628+
).rejects.toBe(providerError);
629+
630+
expect(deliveredPath).toBeDefined();
631+
expect(fs.existsSync(deliveredPath!)).toBe(false);
632+
expect(fs.readdirSync(openClawState.statePath("media", "outbound"))).toHaveLength(1);
633+
});
634+
563635
it("sends audioAsVoice media through send-attachment audio transport", async () => {
564636
const client = createClient({ message_id: 12345 });
565637
const runCliJson = vi.fn().mockResolvedValueOnce({ messageId: "p:0/voice-guid" });
@@ -1009,6 +1081,44 @@ describe("sendMessageIMessage receipts", () => {
10091081
);
10101082
});
10111083

1084+
it("preserves staged filenames across native RPC sends and their unthreaded retry", async () => {
1085+
const filename = "threaded-review.pdf";
1086+
const attachmentBytes = Buffer.from("actual native rpc provider bytes");
1087+
const sourcePath = createOutboundMediaFile(filename, attachmentBytes);
1088+
const deliveredPaths: string[] = [];
1089+
const client = {
1090+
request: vi.fn(async (_method: string, params: Record<string, unknown>) => {
1091+
const attachmentPath = params.file as string;
1092+
deliveredPaths.push(attachmentPath);
1093+
expect(fs.readFileSync(attachmentPath)).toEqual(attachmentBytes);
1094+
if (params.reply_to) {
1095+
throw new Error(
1096+
"reply_to requires bridge transport; AppleScript fallback cannot send threaded replies",
1097+
);
1098+
}
1099+
return { guid: "p:0/provider-accepted-rpc" };
1100+
}),
1101+
stop: vi.fn(async () => {}),
1102+
} as unknown as IMessageRpcClient;
1103+
1104+
const result = await sendMessageIMessage("chat_id:42", "caption", {
1105+
config: IMESSAGE_TEST_CFG,
1106+
client,
1107+
conversationReadOrigin: "direct-operator",
1108+
replyToId: "p:0/thread-root",
1109+
mediaUrl: sourcePath,
1110+
mediaLocalRoots: [openClawState.root],
1111+
});
1112+
1113+
expect(result.messageId).toBe("p:0/provider-accepted-rpc");
1114+
expect(deliveredPaths.map((attachmentPath) => path.basename(attachmentPath))).toEqual([
1115+
filename,
1116+
filename,
1117+
]);
1118+
expect(deliveredPaths.every((attachmentPath) => !fs.existsSync(attachmentPath))).toBe(true);
1119+
expect(fs.readdirSync(openClawState.statePath("media", "outbound"))).toHaveLength(1);
1120+
});
1121+
10121122
it("sends DM handle media captions as attachment plus follow-up text", async () => {
10131123
const client = createClient({ guid: "p:0/caption-guid" });
10141124
const runCliJson = vi.fn().mockResolvedValueOnce({ messageId: "p:0/dm-media-guid" });
@@ -1046,18 +1156,53 @@ describe("sendMessageIMessage receipts", () => {
10461156
});
10471157

10481158
it("does not persist caption text when the caption follow-up send fails", async () => {
1049-
const client = createRejectingClient(new Error("caption failed"));
1159+
const captionError = new Error("caption failed");
1160+
const client = createRejectingClient(captionError);
10501161
const runCliJson = vi.fn().mockResolvedValueOnce({ messageId: "p:0/dm-media-guid" });
1162+
const onDeliveryResult = vi.fn();
10511163

1052-
await expect(
1053-
sendMessageIMessage("imessage:+15550004567", "caption", {
1164+
let observedError: unknown;
1165+
try {
1166+
await sendMessageIMessage("imessage:+15550004567", "caption", {
10541167
config: IMESSAGE_TEST_CFG,
10551168
client,
10561169
mediaUrl: "/tmp/image.png",
10571170
resolveAttachmentImpl: async () => ({ path: "/tmp/image.png", contentType: "image/png" }),
10581171
runCliJson,
1172+
onDeliveryResult,
1173+
});
1174+
} catch (error) {
1175+
observedError = error;
1176+
}
1177+
1178+
expect(isChannelPartialDeliveryError(observedError)).toBe(true);
1179+
expect(observedError).toMatchObject({
1180+
code: "CHANNEL_PARTIAL_DELIVERY",
1181+
cause: captionError,
1182+
sentBeforeError: true,
1183+
visibleReplySent: true,
1184+
deliveryResult: {
1185+
content: "",
1186+
messageIds: ["p:0/dm-media-guid"],
1187+
receipt: {
1188+
primaryPlatformMessageId: "p:0/dm-media-guid",
1189+
platformMessageIds: ["p:0/dm-media-guid"],
1190+
parts: [expect.objectContaining({ kind: "media" })],
1191+
},
1192+
visibleReplySent: true,
1193+
},
1194+
});
1195+
expect(onDeliveryResult).toHaveBeenCalledExactlyOnceWith(
1196+
expect.objectContaining({
1197+
content: "",
1198+
messageId: "p:0/dm-media-guid",
1199+
messageIds: ["p:0/dm-media-guid"],
1200+
visibleReplySent: true,
1201+
receipt: expect.objectContaining({
1202+
platformMessageIds: ["p:0/dm-media-guid"],
1203+
}),
10591204
}),
1060-
).rejects.toThrow("caption failed");
1205+
);
10611206
const scope = "default:imessage:+15550004567";
10621207
expect(hasPersistedIMessageEcho({ scope, text: "caption" })).toBe(false);
10631208
expect(
@@ -1066,6 +1211,41 @@ describe("sendMessageIMessage receipts", () => {
10661211
expect(hasPersistedIMessageEcho({ scope, messageId: "p:0/dm-media-guid" })).toBe(true);
10671212
});
10681213

1214+
it("stops before a caption when accepted attachment custody cannot be recorded", async () => {
1215+
const custodyError = new Error("accepted attachment custody failed");
1216+
const client = createClient({ guid: "p:0/caption-guid" });
1217+
const runCliJson = vi.fn().mockResolvedValueOnce({ messageId: "p:0/dm-media-guid" });
1218+
const onDeliveryResult = vi.fn(async () => {
1219+
throw custodyError;
1220+
});
1221+
1222+
await expect(
1223+
sendMessageIMessage("imessage:+15550004567", "caption", {
1224+
config: IMESSAGE_TEST_CFG,
1225+
client,
1226+
mediaUrl: "/tmp/image.png",
1227+
resolveAttachmentImpl: async () => ({ path: "/tmp/image.png", contentType: "image/png" }),
1228+
runCliJson,
1229+
onDeliveryResult,
1230+
}),
1231+
).rejects.toBe(custodyError);
1232+
1233+
expect(isChannelPartialDeliveryError(custodyError)).toBe(false);
1234+
expect(runCliJson).toHaveBeenCalledOnce();
1235+
expect(getClientMocks(client).request).not.toHaveBeenCalled();
1236+
expect(onDeliveryResult).toHaveBeenCalledExactlyOnceWith(
1237+
expect.objectContaining({
1238+
content: "",
1239+
messageId: "p:0/dm-media-guid",
1240+
messageIds: ["p:0/dm-media-guid"],
1241+
receipt: expect.objectContaining({
1242+
platformMessageIds: ["p:0/dm-media-guid"],
1243+
}),
1244+
visibleReplySent: true,
1245+
}),
1246+
);
1247+
});
1248+
10691249
it("returns the caption message id when captioned attachment only has a placeholder id", async () => {
10701250
const client = createClient({ guid: "p:0/caption-guid" });
10711251
const runCliJson = vi.fn().mockResolvedValueOnce({ success: true });

0 commit comments

Comments
 (0)