Compare commits

...

2 Commits

Author SHA1 Message Date
Peter Steinberger
b782ae104d fix: imessage echo detection ids (#8680) (thanks @Iranb) 2026-02-04 03:31:08 -08:00
iranb
27525586b2 fix(imessage): detect self-chat echoes to prevent infinite loops 2026-02-04 03:25:31 -08:00
5 changed files with 155 additions and 4 deletions

View File

@@ -18,6 +18,7 @@ Docs: https://docs.openclaw.ai
### Fixes
- Telegram: honor session model overrides in inline model selection. (#8193) Thanks @gildo.
- iMessage: skip echo replies using recent outbound IDs before falling back to text matching. (#8680) Thanks @Iranb.
- Web UI: resolve header logo path when `gateway.controlUi.basePath` is set. (#7178) Thanks @Yeom-JinHo.
- Web UI: apply button styling to the new-messages indicator.
- Security: keep untrusted channel metadata out of system prompts (Slack/Discord). Thanks @KonstantinMirin.

View File

@@ -101,6 +101,47 @@ beforeEach(() => {
});
describe("monitorIMessageProvider", () => {
it("skips echo messages that match recent outbound ids", async () => {
sendMock.mockResolvedValue({ messageId: "123" });
const run = monitorIMessageProvider();
await waitForSubscribe();
notificationHandler?.({
method: "message",
params: {
message: {
id: 1,
sender: "+15550001111",
is_from_me: false,
text: "ping",
is_group: false,
},
},
});
await flush();
notificationHandler?.({
method: "message",
params: {
message: {
id: 123,
sender: "+15550001111",
is_from_me: false,
text: "ok",
is_group: false,
},
},
});
await flush();
closeResolve?.();
await run;
expect(replyMock).toHaveBeenCalledTimes(1);
expect(sendMock).toHaveBeenCalledTimes(1);
});
it("skips group messages without a mention by default", async () => {
const run = monitorIMessageProvider();
await waitForSubscribe();

View File

@@ -6,6 +6,7 @@ import { loadConfig } from "../../config/config.js";
import { resolveMarkdownTableMode } from "../../config/markdown-tables.js";
import { convertMarkdownTables } from "../../markdown/tables.js";
import { sendMessageIMessage } from "../send.js";
import { buildIMessageEchoScope, type SentMessageCache } from "./echo-cache.js";
export async function deliverReplies(params: {
replies: ReplyPayload[];
@@ -15,8 +16,11 @@ export async function deliverReplies(params: {
runtime: RuntimeEnv;
maxBytes: number;
textLimit: number;
sentMessageCache?: SentMessageCache;
}) {
const { replies, target, client, runtime, maxBytes, textLimit, accountId } = params;
const { replies, target, client, runtime, maxBytes, textLimit, accountId, sentMessageCache } =
params;
const scope = buildIMessageEchoScope({ accountId, target });
const cfg = loadConfig();
const tableMode = resolveMarkdownTableMode({
cfg,
@@ -33,23 +37,29 @@ export async function deliverReplies(params: {
}
if (mediaList.length === 0) {
for (const chunk of chunkTextWithMode(text, textLimit, chunkMode)) {
await sendMessageIMessage(target, chunk, {
const result = await sendMessageIMessage(target, chunk, {
maxBytes,
client,
accountId,
});
sentMessageCache?.rememberText(scope, chunk);
sentMessageCache?.rememberId(scope, result.messageId);
}
} else {
let first = true;
for (const url of mediaList) {
const caption = first ? text : "";
first = false;
await sendMessageIMessage(target, caption, {
const result = await sendMessageIMessage(target, caption, {
mediaUrl: url,
maxBytes,
client,
accountId,
});
if (caption) {
sentMessageCache?.rememberText(scope, caption);
}
sentMessageCache?.rememberId(scope, result.messageId);
}
}
runtime.log?.(`imessage: delivered reply to ${target}`);

View File

@@ -0,0 +1,78 @@
export function buildIMessageEchoScope(params: {
accountId?: string | null;
target: string;
}): string {
return `${params.accountId ?? ""}:${params.target}`;
}
type CacheEntry = Map<string, number>;
export class SentMessageCache {
private readonly ttlMs: number;
private readonly textCache: CacheEntry = new Map();
private readonly idCache: CacheEntry = new Map();
constructor(opts: { ttlMs?: number } = {}) {
this.ttlMs = opts.ttlMs ?? 5000;
}
rememberText(scope: string, text: string): void {
const trimmed = text?.trim?.() ?? "";
if (!trimmed) {
return;
}
this.textCache.set(this.buildKey(scope, trimmed), Date.now());
this.cleanup(this.textCache);
}
rememberId(scope: string, id: string | number): void {
const normalized = String(id ?? "").trim();
if (!normalized || normalized === "ok" || normalized === "unknown") {
return;
}
this.idCache.set(this.buildKey(scope, normalized), Date.now());
this.cleanup(this.idCache);
}
hasText(scope: string, text: string): boolean {
const trimmed = text?.trim?.() ?? "";
if (!trimmed) {
return false;
}
return this.has(scope, trimmed, this.textCache);
}
hasId(scope: string, id: string | number): boolean {
const normalized = String(id ?? "").trim();
if (!normalized) {
return false;
}
return this.has(scope, normalized, this.idCache);
}
private has(scope: string, value: string, cache: CacheEntry): boolean {
const key = this.buildKey(scope, value);
const timestamp = cache.get(key);
if (!timestamp) {
return false;
}
if (Date.now() - timestamp > this.ttlMs) {
cache.delete(key);
return false;
}
return true;
}
private buildKey(scope: string, value: string): string {
return `${scope}:${value}`;
}
private cleanup(cache: CacheEntry): void {
const now = Date.now();
for (const [key, timestamp] of cache.entries()) {
if (now - timestamp > this.ttlMs) {
cache.delete(key);
}
}
}
}

View File

@@ -53,6 +53,7 @@ import {
normalizeIMessageHandle,
} from "../targets.js";
import { deliverReplies } from "./deliver.js";
import { buildIMessageEchoScope, SentMessageCache } from "./echo-cache.js";
import { normalizeAllowList, resolveRuntime } from "./runtime.js";
/**
@@ -125,6 +126,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
DEFAULT_GROUP_HISTORY_LIMIT,
);
const groupHistories = new Map<string, HistoryEntry[]>();
const sentMessageCache = new SentMessageCache();
const textLimit = resolveTextChunkLimit(cfg, "imessage", accountInfo.accountId);
const allowFrom = normalizeAllowList(opts.allowFrom ?? imessageCfg.allowFrom);
const groupAllowFrom = normalizeAllowList(
@@ -344,7 +346,26 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
},
});
const mentionRegexes = buildMentionRegexes(cfg, route.agentId);
const chatTarget = isGroup ? formatIMessageChatTarget(chatId) : undefined;
const messageText = (message.text ?? "").trim();
const messageId = message.id ?? undefined;
const echoScope = buildIMessageEchoScope({
accountId: accountInfo.accountId,
target: chatTarget ?? `imessage:${sender}`,
});
if (messageId !== undefined && sentMessageCache.hasId(echoScope, messageId)) {
logVerbose(
`imessage: skipping echo message (matches recently sent id within 5s): ${String(messageId)}`,
);
return;
}
if (messageText && sentMessageCache.hasText(echoScope, messageText)) {
logVerbose(
`imessage: skipping echo message (matches recently sent text within 5s): "${truncateUtf16Safe(messageText, 50)}"`,
);
return;
}
const attachments = includeAttachments ? (message.attachments ?? []) : [];
// Filter to valid attachments with paths
const validAttachments = attachments.filter((entry) => entry?.original_path && !entry?.missing);
@@ -437,7 +458,6 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
return;
}
const chatTarget = formatIMessageChatTarget(chatId);
const fromLabel = formatInboundFromLabel({
isGroup,
groupLabel: message.chat_name ?? undefined,
@@ -566,6 +586,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
runtime,
maxBytes: mediaMaxBytes,
textLimit,
sentMessageCache,
});
},
onError: (err, info) => {