Skip to content

Commit 3708934

Browse files
fix(imessage): keep self-chat duplicates out of the loop limiter (#126856)
Preserve ordinary paired self-chat delivery past the five-hit loop threshold while retaining real echo and reflected-content protection. Reuse the monitor integration fixture and consolidate equivalent TTL cases; total LOC is net negative. Co-authored-by: Peter Steinberger <[email protected]>
1 parent 3aef4d5 commit 3708934

3 files changed

Lines changed: 64 additions & 91 deletions

File tree

‎extensions/imessage/src/monitor.last-route.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ describe("iMessage monitor last-route updates", () => {
327327
| "is_from_me"
328328
| "is_group"
329329
| "created_at"
330+
| "destination_caller_id"
330331
>
331332
>,
332333
): IMessagePayload {
@@ -341,6 +342,7 @@ describe("iMessage monitor last-route updates", () => {
341342
text: message.text,
342343
is_group: message.is_group ?? false,
343344
created_at: message.created_at ?? new Date().toISOString(),
345+
destination_caller_id: message.destination_caller_id,
344346
};
345347
}
346348

@@ -683,6 +685,42 @@ describe("iMessage monitor last-route updates", () => {
683685
};
684686
}
685687

688+
it("delivers eight self-chat turns without counting their paired rows as echo loops", async () => {
689+
const runtime = { error: vi.fn(), exit: vi.fn(), log: vi.fn() };
690+
const texts = Array.from({ length: 8 }, (_, index) => `self-chat message ${index + 1}`);
691+
const createdAt = new Date().toISOString();
692+
await runMessageCase({
693+
messages: texts.flatMap((text, index) =>
694+
[true, false].map((isFromMe) =>
695+
createInboundMessage({
696+
id: index * 2 + (isFromMe ? 1 : 2),
697+
guid: `self-chat-${index}-${isFromMe}`,
698+
text,
699+
chat_identifier: DEFAULT_SENDER,
700+
is_from_me: isFromMe,
701+
created_at: createdAt,
702+
destination_caller_id: DEFAULT_SENDER,
703+
}),
704+
),
705+
),
706+
afterNotify: async () => {
707+
await vi.waitFor(() => {
708+
expect(dispatchReplyWithBufferedBlockDispatcherMock).toHaveBeenCalledTimes(texts.length);
709+
});
710+
},
711+
monitor: { runtime },
712+
});
713+
expect(
714+
dispatchReplyWithBufferedBlockDispatcherMock.mock.calls.map(
715+
([params]) => params.ctx.BodyForAgent,
716+
),
717+
).toEqual(texts);
718+
expect(runtime.error).not.toHaveBeenCalled();
719+
expect(
720+
runtime.log.mock.calls.some(([message]) => String(message).includes("rate limiter tripped")),
721+
).toBe(false);
722+
});
723+
686724
it("waits for configured ACP target readiness before dispatching an authorized message", async () => {
687725
let releaseReadiness: ((value: { ok: true }) => void) | undefined;
688726
ensureConfiguredBindingRouteReadyMock.mockImplementationOnce(

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

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -795,16 +795,10 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
795795
const rateLimitKey = `${accountInfo.accountId}:${conversationKey}`;
796796

797797
if (decision.kind === "drop") {
798-
// Record echo/reflection drops so the rate limiter can detect sustained loops.
799-
// Only loop-related drop reasons feed the counter; policy/mention/empty drops
800-
// are normal and should not escalate. "from me" is excluded: every own-send
801-
// (agent replies, multi-chunk sends, operator phone traffic) produces a
802-
// from-me row, so counting it lets a normal outbound burst trip the limiter
803-
// and silently suppress the next legitimate inbound message.
798+
// Count reflected agent content, not ordinary own-send or self-chat dedupe
799+
// rows: counting those benign drops mutes legitimate conversation bursts.
804800
const isLoopDrop =
805-
decision.reason === "echo" ||
806-
decision.reason === "self-chat echo" ||
807-
decision.reason === "reflected assistant content";
801+
decision.reason === "echo" || decision.reason === "reflected assistant content";
808802
if (isLoopDrop) {
809803
loopRateLimiter.record(rateLimitKey);
810804
}

‎extensions/imessage/src/monitor/self-chat-dedupe.test.ts‎

Lines changed: 23 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -150,40 +150,16 @@ describe("echo cache — backward compat for channels without messageId", () =>
150150
// Proves text-fallback echo detection still works when no messageId is present
151151
// on either side. Critical for backward compat with channels that don't
152152
// populate messageId.
153-
it("text-only remember/has works within TTL", async () => {
153+
it.each([
154+
{ label: "within TTL", elapsed: 2000, text: "no id message", expected: true },
155+
{ label: "after TTL expiry", elapsed: 5000, text: "no id message", expected: false },
156+
{ label: "for different text", elapsed: 1000, text: "totally different text", expected: false },
157+
])("matches text-only echoes $label: $expected", ({ elapsed, text, expected }) => {
154158
useFakeTimersAt();
155-
156159
const echoCache = createSentMessageCache();
157-
const scope = "default:imessage:+15555550123";
158-
159-
echoCache.remember(scope, { text: "no id message" });
160-
161-
vi.advanceTimersByTime(2000);
162-
expect(echoCache.has(scope, { text: "no id message" })).toBe(true);
163-
});
164-
165-
it("text-only has returns false after TTL expiry", async () => {
166-
useFakeTimersAt();
167-
168-
const echoCache = createSentMessageCache();
169-
const scope = "default:imessage:+15555550123";
170-
171-
echoCache.remember(scope, { text: "no id message" });
172-
173-
vi.advanceTimersByTime(5000);
174-
expect(echoCache.has(scope, { text: "no id message" })).toBe(false);
175-
});
176-
177-
it("text-only has returns false for different text", async () => {
178-
useFakeTimersAt();
179-
180-
const echoCache = createSentMessageCache();
181-
const scope = "default:imessage:+15555550123";
182-
183-
echoCache.remember(scope, { text: "no id message" });
184-
185-
vi.advanceTimersByTime(1000);
186-
expect(echoCache.has(scope, { text: "totally different text" })).toBe(false);
160+
echoCache.remember(SELF_CHAT_SCOPE, { text: "no id message" });
161+
vi.advanceTimersByTime(elapsed);
162+
expect(echoCache.has(SELF_CHAT_SCOPE, { text })).toBe(expected);
187163
});
188164
});
189165

@@ -285,56 +261,21 @@ describe("self-chat dedupe — #47830", () => {
285261
expect(decision.kind).toBe("dispatch");
286262
});
287263

288-
it("drops echo after text TTL expiry (4s TTL: expired at 5s)", async () => {
289-
useFakeTimersAt();
290-
291-
const echoCache = createSentMessageCache();
292-
const scope = "default:imessage:+15555550123";
293-
294-
// Agent sends text (no message id available)
295-
echoCache.remember(scope, { text: "Hello there" });
296-
297-
// After 5 seconds — beyond the 4s TTL, should NOT match
298-
vi.advanceTimersByTime(5000);
299-
300-
const result = echoCache.has(scope, { text: "Hello there" });
301-
expect(result).toBe(false);
302-
});
303-
304-
// Safe failure mode: TTL expiry causes duplicate delivery (noisy), never message loss (lossy)
305-
it("does NOT catch echo after TTL expiry — safe failure mode is duplicate delivery", async () => {
306-
useFakeTimersAt();
307-
308-
const echoCache = createSentMessageCache();
309-
const scope = SELF_CHAT_SCOPE;
310-
311-
// Agent sends "Delayed echo test"
312-
echoCache.remember(scope, { text: "Delayed echo test", messageId: "agent-msg-delayed" });
313-
314-
// 4.5 seconds later — beyond 4s TTL
315-
vi.advanceTimersByTime(4500);
316-
317-
// Echo arrives with no messageId (text-only fallback path)
318-
const result = echoCache.has(scope, { text: "Delayed echo test" });
319-
320-
// TTL expired → not caught → duplicate delivery (noisy but safe, not lossy)
321-
expect(result).toBe(false);
322-
});
323-
324-
it("still drops text echo within 4s TTL window", async () => {
325-
useFakeTimersAt();
326-
327-
const echoCache = createSentMessageCache();
328-
const scope = "default:imessage:+15555550123";
329-
330-
echoCache.remember(scope, { text: "Hello there" });
331-
332-
// After 3 seconds — within the 4s TTL, should still match
333-
vi.advanceTimersByTime(3000);
334-
335-
const result = echoCache.has(scope, { text: "Hello there" });
336-
expect(result).toBe(true);
337-
});
264+
// Late text-only matches must expire even when the original send had an ID.
265+
it.each([
266+
{ elapsed: 5000, messageId: undefined, expected: false },
267+
{ elapsed: 4500, messageId: "agent-msg-delayed", expected: false },
268+
{ elapsed: 3000, messageId: undefined, expected: true },
269+
])(
270+
"matches a text-only lookup after $elapsed ms (send ID $messageId): $expected",
271+
({ elapsed, messageId, expected }) => {
272+
useFakeTimersAt();
273+
const echoCache = createSentMessageCache();
274+
echoCache.remember(SELF_CHAT_SCOPE, { text: "Hello there", messageId });
275+
vi.advanceTimersByTime(elapsed);
276+
expect(echoCache.has(SELF_CHAT_SCOPE, { text: "Hello there" })).toBe(expected);
277+
},
278+
);
338279
});
339280

340281
describe("self-chat is_from_me=true handling (Bruce Phase 2 fix)", () => {

0 commit comments

Comments
 (0)