Skip to content

Commit a290f5e

Browse files
authored
fix: persist outbound sends and skip stale cron deliveries (#50092)
* fix(bluebubbles): auto-create chats for new numbers, persist outbound messages to session transcripts Two fixes for BlueBubbles message tool behavior: 1. **Attachment sends to new phone numbers**: sendBlueBubblesAttachment now auto-creates a new DM chat (via /api/v1/chat/new) when no existing chat is found for a handle target, matching the behavior already present in sendMessageBlueBubbles for text sends. The existing createNewChatWithMessage is refactored into a reusable createChatForHandle that returns the chatGuid. 2. **Outbound message session persistence**: Ensures outbound messages sent via the message tool are reliably tracked in session transcripts: - ensureOutboundSessionEntry now falls back to directly creating a session store entry when recordSessionMetaFromInbound returns null, guaranteeing a sessionId exists for the subsequent mirror append. - appendAssistantMessageToSessionTranscript now normalizes the session key (lowercased) when looking up the store, preventing case mismatches between the store keys and the mirror sessionKey. Tests added for all changes. * test(slack): verify outbound session tracking and new target sends for Slack The shared infrastructure changes from the BlueBubbles fix (session key normalization in transcript.ts and fallback session entry creation in outbound-session.ts) already cover Slack. Slack's sendMessageSlack uses conversations.open to auto-create DM channels for new user targets. Add tests confirming: - Slack user DM and channel session route resolution (outbound.test.ts) - Slack session key normalization for transcript append (sessions.test.ts) - Slack outbound sendText/sendMedia to new user and channel targets (channel.test.ts) * fix(cron): skip stale delayed deliveries * fix: prep PR #50092
1 parent ffc1d54 commit a290f5e

12 files changed

Lines changed: 1381 additions & 33 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ Docs: https://docs.openclaw.ai
243243
- Auth/Codex CLI reuse: sync reused Codex CLI credentials into the supported `openai-codex:default` OAuth profile instead of reviving the deprecated `openai-codex:codex-cli` slot, so doctor cleanup no longer loops. (#45353) thanks @Gugu-sugar.
244244
- Deps/audit: bump the pinned `fast-xml-parser` override to the first patched release so `pnpm audit --prod --audit-level=high` no longer fails on the AWS Bedrock XML builder path. Thanks @vincentkoc.
245245
- Hooks/after_compaction: forward `sessionFile` for direct/manual compaction events and add `sessionFile` plus `sessionKey` to wired auto-compaction hook context so plugins receive the session metadata already declared in the hook types. (#40781) Thanks @jarimustonen.
246+
- Sessions/BlueBubbles/cron: persist outbound session routing and transcript mirroring for new targets, auto-create BlueBubbles chats before attachment sends, and only suppress isolated cron deliveries when the run started hours late instead of merely finishing late. (#50092)
246247

247248
### Breaking
248249

‎extensions/bluebubbles/src/attachments.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,4 +484,94 @@ describe("sendBlueBubblesAttachment", () => {
484484
expect(bodyText).not.toContain('name="selectedMessageGuid"');
485485
expect(bodyText).not.toContain('name="partIndex"');
486486
});
487+
488+
it("auto-creates a new chat when sending to a phone number with no existing chat", async () => {
489+
// First call: resolveChatGuidForTarget queries chats, returns empty (no match)
490+
mockFetch.mockResolvedValueOnce({
491+
ok: true,
492+
json: () => Promise.resolve({ data: [] }),
493+
});
494+
// Second call: createChatForHandle creates new chat
495+
mockFetch.mockResolvedValueOnce({
496+
ok: true,
497+
text: () =>
498+
Promise.resolve(
499+
JSON.stringify({
500+
data: { chatGuid: "iMessage;-;+15559876543", guid: "iMessage;-;+15559876543" },
501+
}),
502+
),
503+
});
504+
// Third call: actual attachment send
505+
mockFetch.mockResolvedValueOnce({
506+
ok: true,
507+
text: () => Promise.resolve(JSON.stringify({ data: { guid: "attach-msg-1" } })),
508+
});
509+
510+
const result = await sendBlueBubblesAttachment({
511+
to: "+15559876543",
512+
buffer: new Uint8Array([1, 2, 3]),
513+
filename: "photo.jpg",
514+
contentType: "image/jpeg",
515+
opts: { serverUrl: "http://localhost:1234", password: "test" },
516+
});
517+
518+
expect(result.messageId).toBe("attach-msg-1");
519+
// Verify chat creation was called
520+
const createCallBody = JSON.parse(mockFetch.mock.calls[1][1].body);
521+
expect(createCallBody.addresses).toEqual(["+15559876543"]);
522+
// Verify attachment was sent to the newly created chat
523+
const attachBody = mockFetch.mock.calls[2][1]?.body as Uint8Array;
524+
const attachText = decodeBody(attachBody);
525+
expect(attachText).toContain("iMessage;-;+15559876543");
526+
});
527+
528+
it("retries chatGuid resolution after creating a chat with no returned guid", async () => {
529+
mockFetch.mockResolvedValueOnce({
530+
ok: true,
531+
json: () => Promise.resolve({ data: [] }),
532+
});
533+
mockFetch.mockResolvedValueOnce({
534+
ok: true,
535+
text: () => Promise.resolve(JSON.stringify({ data: {} })),
536+
});
537+
mockFetch.mockResolvedValueOnce({
538+
ok: true,
539+
json: () => Promise.resolve({ data: [{ guid: "iMessage;-;+15557654321" }] }),
540+
});
541+
mockFetch.mockResolvedValueOnce({
542+
ok: true,
543+
text: () => Promise.resolve(JSON.stringify({ data: { guid: "attach-msg-2" } })),
544+
});
545+
546+
const result = await sendBlueBubblesAttachment({
547+
to: "+15557654321",
548+
buffer: new Uint8Array([4, 5, 6]),
549+
filename: "photo.jpg",
550+
contentType: "image/jpeg",
551+
opts: { serverUrl: "http://localhost:1234", password: "test" },
552+
});
553+
554+
expect(result.messageId).toBe("attach-msg-2");
555+
const createCallBody = JSON.parse(mockFetch.mock.calls[1][1].body);
556+
expect(createCallBody.addresses).toEqual(["+15557654321"]);
557+
const attachBody = mockFetch.mock.calls[3][1]?.body as Uint8Array;
558+
const attachText = decodeBody(attachBody);
559+
expect(attachText).toContain("iMessage;-;+15557654321");
560+
});
561+
562+
it("still throws for non-handle targets when chatGuid is not found", async () => {
563+
mockFetch.mockResolvedValueOnce({
564+
ok: true,
565+
json: () => Promise.resolve({ data: [] }),
566+
});
567+
568+
await expect(
569+
sendBlueBubblesAttachment({
570+
to: "chat_id:999",
571+
buffer: new Uint8Array([1, 2, 3]),
572+
filename: "photo.jpg",
573+
opts: { serverUrl: "http://localhost:1234", password: "test" },
574+
}),
575+
).rejects.toThrow("chatGuid not found");
576+
});
487577
});

‎extensions/bluebubbles/src/attachments.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { resolveRequestUrl } from "./request-url.js";
1010
import type { OpenClawConfig } from "./runtime-api.js";
1111
import { getBlueBubblesRuntime, warnBlueBubbles } from "./runtime.js";
1212
import { extractBlueBubblesMessageId, resolveBlueBubblesSendTarget } from "./send-helpers.js";
13-
import { resolveChatGuidForTarget } from "./send.js";
13+
import { resolveChatGuidForTarget, createChatForHandle } from "./send.js";
1414
import {
1515
blueBubblesFetchWithTimeout,
1616
buildBlueBubblesApiUrl,
@@ -180,16 +180,37 @@ export async function sendBlueBubblesAttachment(params: {
180180
}
181181

182182
const target = resolveBlueBubblesSendTarget(to);
183-
const chatGuid = await resolveChatGuidForTarget({
183+
let chatGuid = await resolveChatGuidForTarget({
184184
baseUrl,
185185
password,
186186
timeoutMs: opts.timeoutMs,
187187
target,
188188
});
189189
if (!chatGuid) {
190-
throw new Error(
191-
"BlueBubbles attachment send failed: chatGuid not found for target. Use a chat_guid target or ensure the chat exists.",
192-
);
190+
// For handle targets (phone numbers/emails), auto-create a new DM chat
191+
if (target.kind === "handle") {
192+
const created = await createChatForHandle({
193+
baseUrl,
194+
password,
195+
address: target.address,
196+
timeoutMs: opts.timeoutMs,
197+
});
198+
chatGuid = created.chatGuid;
199+
// If we still don't have a chatGuid, try resolving again (chat was created server-side)
200+
if (!chatGuid) {
201+
chatGuid = await resolveChatGuidForTarget({
202+
baseUrl,
203+
password,
204+
timeoutMs: opts.timeoutMs,
205+
target,
206+
});
207+
}
208+
}
209+
if (!chatGuid) {
210+
throw new Error(
211+
"BlueBubbles attachment send failed: chatGuid not found for target. Use a chat_guid target or ensure the chat exists.",
212+
);
213+
}
193214
}
194215

195216
const url = buildBlueBubblesApiUrl({

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

Lines changed: 106 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
33
import "./test-mocks.js";
44
import { getCachedBlueBubblesPrivateApiStatus } from "./probe.js";
55
import { clearBlueBubblesRuntime, setBlueBubblesRuntime } from "./runtime.js";
6-
import { sendMessageBlueBubbles, resolveChatGuidForTarget } from "./send.js";
6+
import { sendMessageBlueBubbles, resolveChatGuidForTarget, createChatForHandle } from "./send.js";
77
import {
88
BLUE_BUBBLES_PRIVATE_API_STATUS,
99
installBlueBubblesFetchTestHooks,
@@ -781,4 +781,109 @@ describe("send", () => {
781781
expect(body.tempGuid.length).toBeGreaterThan(0);
782782
});
783783
});
784+
785+
describe("createChatForHandle", () => {
786+
it("creates a new chat and returns chatGuid from response", async () => {
787+
mockFetch.mockResolvedValueOnce({
788+
ok: true,
789+
text: () =>
790+
Promise.resolve(
791+
JSON.stringify({
792+
data: { guid: "iMessage;-;+15559876543", chatGuid: "iMessage;-;+15559876543" },
793+
}),
794+
),
795+
});
796+
797+
const result = await createChatForHandle({
798+
baseUrl: "http://localhost:1234",
799+
password: "test",
800+
address: "+15559876543",
801+
message: "Hello!",
802+
});
803+
804+
expect(result.chatGuid).toBe("iMessage;-;+15559876543");
805+
expect(result.messageId).toBeDefined();
806+
const body = JSON.parse(mockFetch.mock.calls[0][1].body);
807+
expect(body.addresses).toEqual(["+15559876543"]);
808+
expect(body.message).toBe("Hello!");
809+
});
810+
811+
it("creates a new chat without a message when message is omitted", async () => {
812+
mockFetch.mockResolvedValueOnce({
813+
ok: true,
814+
text: () =>
815+
Promise.resolve(
816+
JSON.stringify({
817+
data: { guid: "iMessage;-;+15559876543" },
818+
}),
819+
),
820+
});
821+
822+
const result = await createChatForHandle({
823+
baseUrl: "http://localhost:1234",
824+
password: "test",
825+
address: "+15559876543",
826+
});
827+
828+
expect(result.chatGuid).toBe("iMessage;-;+15559876543");
829+
const body = JSON.parse(mockFetch.mock.calls[0][1].body);
830+
expect(body.message).toBe("");
831+
});
832+
833+
it.each([
834+
["data.chatGuid", { data: { chatGuid: "shape-chat-guid" } }, "shape-chat-guid"],
835+
["data.guid", { data: { guid: "shape-guid" } }, "shape-guid"],
836+
[
837+
"data.chats[0].guid",
838+
{ data: { chats: [{ guid: "shape-array-guid" }] } },
839+
"shape-array-guid",
840+
],
841+
["data.chat.guid", { data: { chat: { guid: "shape-object-guid" } } }, "shape-object-guid"],
842+
])("extracts chatGuid from %s", async (_label, responseBody, expectedChatGuid) => {
843+
mockFetch.mockResolvedValueOnce({
844+
ok: true,
845+
text: () => Promise.resolve(JSON.stringify(responseBody)),
846+
});
847+
848+
const result = await createChatForHandle({
849+
baseUrl: "http://localhost:1234",
850+
password: "test",
851+
address: "+15559876543",
852+
});
853+
854+
expect(result.chatGuid).toBe(expectedChatGuid);
855+
});
856+
857+
it("throws when Private API is not enabled", async () => {
858+
mockFetch.mockResolvedValueOnce({
859+
ok: false,
860+
status: 403,
861+
text: () => Promise.resolve("Private API not enabled"),
862+
});
863+
864+
await expect(
865+
createChatForHandle({
866+
baseUrl: "http://localhost:1234",
867+
password: "test",
868+
address: "+15559876543",
869+
}),
870+
).rejects.toThrow("Private API must be enabled");
871+
});
872+
873+
it("returns null chatGuid when response has no chat data", async () => {
874+
mockFetch.mockResolvedValueOnce({
875+
ok: true,
876+
text: () => Promise.resolve(JSON.stringify({ data: {} })),
877+
});
878+
879+
const result = await createChatForHandle({
880+
baseUrl: "http://localhost:1234",
881+
password: "test",
882+
address: "+15559876543",
883+
message: "Hello",
884+
});
885+
886+
expect(result.chatGuid).toBeNull();
887+
});
888+
});
784889
});

‎extensions/bluebubbles/src/send.ts‎

Lines changed: 67 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -312,24 +312,28 @@ export async function resolveChatGuidForTarget(params: {
312312
}
313313

314314
/**
315-
* Creates a new chat (DM) and optionally sends an initial message.
315+
* Creates a new DM chat for the given address and returns the chat GUID.
316316
* Requires Private API to be enabled in BlueBubbles.
317+
*
318+
* If a `message` is provided it is sent as the initial message in the new chat;
319+
* otherwise an empty-string message body is used (BlueBubbles still creates the
320+
* chat but will not deliver a visible bubble).
317321
*/
318-
async function createNewChatWithMessage(params: {
322+
export async function createChatForHandle(params: {
319323
baseUrl: string;
320324
password: string;
321325
address: string;
322-
message: string;
326+
message?: string;
323327
timeoutMs?: number;
324-
}): Promise<BlueBubblesSendResult> {
328+
}): Promise<{ chatGuid: string | null; messageId: string }> {
325329
const url = buildBlueBubblesApiUrl({
326330
baseUrl: params.baseUrl,
327331
path: "/api/v1/chat/new",
328332
password: params.password,
329333
});
330334
const payload = {
331335
addresses: [params.address],
332-
message: params.message,
336+
message: params.message ?? "",
333337
tempGuid: `temp-${crypto.randomUUID()}`,
334338
};
335339
const res = await blueBubblesFetchWithTimeout(
@@ -343,7 +347,6 @@ async function createNewChatWithMessage(params: {
343347
);
344348
if (!res.ok) {
345349
const errorText = await res.text();
346-
// Check for Private API not enabled error
347350
if (
348351
res.status === 400 ||
349352
res.status === 403 ||
@@ -355,7 +358,64 @@ async function createNewChatWithMessage(params: {
355358
}
356359
throw new Error(`BlueBubbles create chat failed (${res.status}): ${errorText || "unknown"}`);
357360
}
358-
return parseBlueBubblesMessageResponse(res);
361+
const body = await res.text();
362+
let messageId = "ok";
363+
let chatGuid: string | null = null;
364+
if (body) {
365+
try {
366+
const parsed = JSON.parse(body) as Record<string, unknown>;
367+
messageId = extractBlueBubblesMessageId(parsed);
368+
// Extract chatGuid from the response data
369+
const data = parsed.data as Record<string, unknown> | undefined;
370+
if (data) {
371+
chatGuid =
372+
(typeof data.chatGuid === "string" && data.chatGuid) ||
373+
(typeof data.guid === "string" && data.guid) ||
374+
null;
375+
// Also try nested chats array (some BB versions nest it)
376+
if (!chatGuid) {
377+
const chats = data.chats ?? data.chat;
378+
if (Array.isArray(chats) && chats.length > 0) {
379+
const first = chats[0] as Record<string, unknown> | undefined;
380+
chatGuid =
381+
(typeof first?.guid === "string" && first.guid) ||
382+
(typeof first?.chatGuid === "string" && first.chatGuid) ||
383+
null;
384+
} else if (chats && typeof chats === "object" && !Array.isArray(chats)) {
385+
const chatObj = chats as Record<string, unknown>;
386+
chatGuid =
387+
(typeof chatObj.guid === "string" && chatObj.guid) ||
388+
(typeof chatObj.chatGuid === "string" && chatObj.chatGuid) ||
389+
null;
390+
}
391+
}
392+
}
393+
} catch {
394+
// ignore parse errors
395+
}
396+
}
397+
return { chatGuid, messageId };
398+
}
399+
400+
/**
401+
* Creates a new chat (DM) and sends an initial message.
402+
* Requires Private API to be enabled in BlueBubbles.
403+
*/
404+
async function createNewChatWithMessage(params: {
405+
baseUrl: string;
406+
password: string;
407+
address: string;
408+
message: string;
409+
timeoutMs?: number;
410+
}): Promise<BlueBubblesSendResult> {
411+
const result = await createChatForHandle({
412+
baseUrl: params.baseUrl,
413+
password: params.password,
414+
address: params.address,
415+
message: params.message,
416+
timeoutMs: params.timeoutMs,
417+
});
418+
return { messageId: result.messageId };
359419
}
360420

361421
export async function sendMessageBlueBubbles(

0 commit comments

Comments
 (0)