Skip to content

Commit c25671c

Browse files
authored
fix(imessage): stop dropping user text that collides with recent outbound sends (#120260)
* fix(imessage): text echo matching honors message-id conflicts; own sends stop feeding the loop limiter Two silent-drop paths in the iMessage monitor: 1. The persisted 12h echo cache matched inbound user text against old outbound text even when the GUIDs conflicted — a user sending 'ok' within 12h of the agent sending 'ok' was dropped as an echo. The text branch now applies the same hasConflictingMessageIds guard the media branch has; genuine reconnect echoes still match by id or id-less entries. 2. Every from-me row fed the echo loop rate limiter, so a normal outbound burst (agent replies, multi-chunk sends, operator phone traffic) could trip the limiter and silently suppress the next legitimate inbound message. 'from me' is no longer counted as a loop signal, and a tripped limiter now logs a default-level warning once per conversation instead of verbose-only. * fix(imessage): preserve delayed echo guards
1 parent a68ff99 commit c25671c

5 files changed

Lines changed: 119 additions & 5 deletions

File tree

‎extensions/imessage/src/monitor.watch-subscribe-retry.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
// Imessage tests cover monitor.watch subscribe retry plugin behavior.
2+
import { redactIdentifier } from "openclaw/plugin-sdk/logging-core";
23
import type { waitForTransportReady } from "openclaw/plugin-sdk/transport-ready-runtime";
34
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
45
import type { createIMessageRpcClient, IMessageRpcClient } from "./client.js";
56
import { monitorIMessageProvider } from "./monitor.js";
67
import type { attachIMessageMonitorAbortHandler } from "./monitor/abort-handler.js";
8+
import { rememberPersistedIMessageEcho } from "./monitor/persisted-echo-cache.js";
79
import {
810
installIMessageFailingStateRuntimeForTest,
911
installIMessageStateRuntimeForTest,
@@ -33,6 +35,7 @@ function createRuntime() {
3335
return {
3436
log: vi.fn(),
3537
error: vi.fn(),
38+
exit: vi.fn(),
3639
};
3740
}
3841

@@ -269,4 +272,60 @@ describe("monitorIMessageProvider watch.subscribe startup retry", () => {
269272
expect(diagnostics[0]).not.toContain("private message text");
270273
expect(diagnostics[0]).not.toContain("+15550001111");
271274
});
275+
276+
it("redacts the conversation identifier in rate-limit suppression warnings", async () => {
277+
vi.useRealTimers();
278+
installIMessageStateRuntimeForTest();
279+
const runtime = createRuntime();
280+
const sender = "+15550002222";
281+
const chatId = 456;
282+
const scope = `default:chat_id:${chatId}`;
283+
rememberPersistedIMessageEcho({ scope, text: "loop echo" });
284+
let onNotification:
285+
| ((message: { method: string; params: unknown }) => void | Promise<void>)
286+
| undefined;
287+
const notify = async (id: number, text: string) => {
288+
await onNotification?.({
289+
method: "message",
290+
params: {
291+
message: {
292+
id,
293+
guid: `p:0/message-${id}`,
294+
chat_id: chatId,
295+
sender,
296+
is_from_me: false,
297+
is_group: true,
298+
text,
299+
created_at: new Date().toISOString(),
300+
},
301+
},
302+
});
303+
};
304+
const client = createRpcClient({
305+
waitForClose: async () => {
306+
for (let id = 1; id <= 5; id += 1) {
307+
await notify(id, "loop echo");
308+
}
309+
await notify(6, "legitimate inbound");
310+
},
311+
});
312+
createIMessageRpcClientMock.mockImplementation(async (params) => {
313+
onNotification = params?.onNotification;
314+
return client;
315+
});
316+
317+
await monitorIMessageProvider({
318+
config: { channels: { imessage: { groupPolicy: "open" } } },
319+
runtime,
320+
});
321+
322+
await new Promise((resolve) => {
323+
setTimeout(resolve, 50);
324+
});
325+
const logs = runtime.log.mock.calls.map(([message]) => String(message));
326+
const warning = logs.find((message) => message.includes("rate limiter tripped"));
327+
expect(warning, `logs: ${JSON.stringify(logs)}`).toBeDefined();
328+
expect(warning).toContain(`group:${redactIdentifier(`group:${chatId}`)}`);
329+
expect(warning).not.toContain(sender);
330+
});
272331
});

‎extensions/imessage/src/monitor/echo-cache.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ class DefaultSentMessageCache implements SentMessageCache {
102102
text: lookup.text,
103103
media: lookup.media,
104104
messageId: lookup.messageId,
105+
skipIdShortCircuit: resolvedOptions.skipIdShortCircuit,
105106
includePendingText: resolvedOptions.includePendingText,
106107
})
107108
) {

‎extensions/imessage/src/monitor/monitor-provider.echo-cache.test-support.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,38 @@ describe("iMessage sent-message echo cache", () => {
167167
).toBe(true);
168168
});
169169

170+
it("does not match persisted text when both message ids differ", () => {
171+
// Outbound "ok" recorded with its GUID; a user later sends "ok" with a new
172+
// GUID. Same text, conflicting ids — a NEW message, not a reconnect echo.
173+
const scope = "acct:imessage:+1555";
174+
rememberPersistedIMessageEcho({ scope, text: "ok", messageId: "guid-agent-text" });
175+
176+
expect(hasPersistedIMessageEcho({ scope, text: "ok", messageId: "guid-user-text" })).toBe(
177+
false,
178+
);
179+
// Genuine echo still matches by id, and id-less probes still match by text.
180+
expect(hasPersistedIMessageEcho({ scope, text: "ok", messageId: "guid-agent-text" })).toBe(
181+
true,
182+
);
183+
expect(hasPersistedIMessageEcho({ scope, text: "ok" })).toBe(true);
184+
});
185+
186+
it("matches persisted self-chat text after the in-memory cache expires", () => {
187+
vi.useFakeTimers();
188+
vi.setSystemTime(new Date("2026-02-25T00:00:00Z"));
189+
const scope = "acct:imessage:+1555";
190+
const cache = createSentMessageCache();
191+
const text = "Delayed self-chat echo";
192+
const outboundGuid = "p:0/guid-agent-text";
193+
194+
rememberPersistedIMessageEcho({ scope, text, messageId: outboundGuid });
195+
cache.remember(scope, { text, messageId: outboundGuid });
196+
vi.advanceTimersByTime(4_001);
197+
198+
expect(cache.has(scope, { text, messageId: "12345" }, { skipIdShortCircuit: true })).toBe(true);
199+
expect(cache.has(scope, { text, messageId: "p:0/guid-user-text" })).toBe(false);
200+
});
201+
170202
it("matches persisted media through the primary sent-message cache", () => {
171203
const scope = "acct:imessage:+1555";
172204
const media = { contentType: "image/png", kind: "image" as const };

‎extensions/imessage/src/monitor/monitor-provider.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
2828
import { channelReadyPatch } from "openclaw/plugin-sdk/gateway-runtime";
2929
import { normalizeScpRemoteHost } from "openclaw/plugin-sdk/host-runtime";
30+
import { redactIdentifier } from "openclaw/plugin-sdk/logging-core";
3031
import { isInboundPathAllowed, kindFromMime } from "openclaw/plugin-sdk/media-runtime";
3132
import { DEFAULT_GROUP_HISTORY_LIMIT, type HistoryEntry } from "openclaw/plugin-sdk/reply-history";
3233
import { resolveTextChunkLimit, type GetReplyOptions } from "openclaw/plugin-sdk/reply-runtime";
@@ -827,12 +828,14 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
827828
if (decision.kind === "drop") {
828829
// Record echo/reflection drops so the rate limiter can detect sustained loops.
829830
// Only loop-related drop reasons feed the counter; policy/mention/empty drops
830-
// are normal and should not escalate.
831+
// are normal and should not escalate. "from me" is excluded: every own-send
832+
// (agent replies, multi-chunk sends, operator phone traffic) produces a
833+
// from-me row, so counting it lets a normal outbound burst trip the limiter
834+
// and silently suppress the next legitimate inbound message.
831835
const isLoopDrop =
832836
decision.reason === "echo" ||
833837
decision.reason === "self-chat echo" ||
834-
decision.reason === "reflected assistant content" ||
835-
decision.reason === "from me";
838+
decision.reason === "reflected assistant content";
836839
if (isLoopDrop) {
837840
loopRateLimiter.record(rateLimitKey);
838841
}
@@ -868,7 +871,17 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
868871
// remaining messages as a safety net against amplification that slips
869872
// through the primary guards.
870873
if (decision.kind === "dispatch" && loopRateLimiter.isRateLimited(rateLimitKey)) {
871-
logVerbose(`imessage: rate-limited conversation ${conversationKey} (echo loop detected)`);
874+
// A tripped limiter silently eats real user messages — surface it at
875+
// default log level (once per conversation) instead of verbose-only.
876+
if (!loggedThrottledDropDiagnostics.check(`${rateLimitKey}:rate-limited`)) {
877+
const conversationKind = chatId != null ? "group" : "dm";
878+
const diagnosticConversationKey = `${conversationKind}:${redactIdentifier(conversationKey)}`;
879+
runtime.log?.(
880+
warn(
881+
`[imessage:${accountInfo.accountId}] Suppressing inbound from ${diagnosticConversationKey}: echo loop detected (rate limiter tripped)`,
882+
),
883+
);
884+
}
872885
return;
873886
}
874887

‎extensions/imessage/src/monitor/persisted-echo-cache.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@ export function hasPersistedIMessageEcho(params: {
207207
text?: string;
208208
media?: MediaPlaceholderTextFact;
209209
messageId?: string;
210+
skipIdShortCircuit?: boolean;
210211
includePendingText?: boolean;
211212
}): boolean {
212213
const text = normalizeText(params.text);
@@ -225,7 +226,15 @@ export function hasPersistedIMessageEcho(params: {
225226
const hasConflictingMessageIds = Boolean(
226227
messageId && entry.messageId && messageId !== entry.messageId,
227228
);
228-
if (text && entry.text === text && (!entry.pending || params.includePendingText)) {
229+
// Same-id echoes match on the messageId branch above. Known conflicting
230+
// GUIDs identify new messages, while no-GUID self-chat rows opt into text
231+
// fallback because their numeric SQLite IDs cannot equal outbound GUIDs.
232+
if (
233+
text &&
234+
(!hasConflictingMessageIds || params.skipIdShortCircuit) &&
235+
entry.text === text &&
236+
(!entry.pending || params.includePendingText)
237+
) {
229238
return true;
230239
}
231240
if (

0 commit comments

Comments
 (0)