Skip to content

Commit eb38d5e

Browse files
authored
fix(reply): report settled delivery outcomes once (#124773)
* refactor(reply): publish settled dispatch receipts * refactor(reply): isolate dispatch outcome accounting * refactor(discord): infer settled dispatch result * test(reply): model settled dispatch receipts * test(reply): type settled receipt fixtures * test(telegram): declare settled final receipt * test(telegram): adapt legacy dispatch fixtures * fix(reply): complete settled receipt compatibility * test(channels): keep delivery suite within lint budget * test(channels): reuse settled count fixture * test(channels): consolidate receipt assertions * test(channels): extract delivery receipt fixtures * fix(qa): recover stopped clients after config restart * fix(reply): settle deferred delivery receipts * test(channels): share delivery turn fixtures * fix(channels): preserve non-visible reconciliation * fix(reply): preserve settled receipt compatibility * refactor(reply): make settled receipts canonical * refactor(reply): absorb settlement at dispatcher boundary * test(matrix): prove settled receipt precedence * refactor(sessions): extract prompt snapshot types * fix(reply): restore queued admission counts
1 parent bc277fa commit eb38d5e

71 files changed

Lines changed: 1673 additions & 1002 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎extensions/discord/src/monitor/message-handler.process.ack.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,33 @@ import {
2929
requireRecord,
3030
} from "./message-handler.process.test-helpers.js";
3131

32+
const failedFinalReceipt = {
33+
counts: {
34+
tool: {
35+
delivered: 0,
36+
deliveredNotVisible: 0,
37+
cancelled: 0,
38+
failedBeforeSend: 0,
39+
failedAfterSend: 0,
40+
},
41+
block: {
42+
delivered: 0,
43+
deliveredNotVisible: 0,
44+
cancelled: 0,
45+
failedBeforeSend: 0,
46+
failedAfterSend: 0,
47+
},
48+
final: {
49+
delivered: 0,
50+
deliveredNotVisible: 0,
51+
cancelled: 0,
52+
failedBeforeSend: 1,
53+
failedAfterSend: 0,
54+
},
55+
},
56+
anyVisibleDelivered: false,
57+
} as const;
58+
3259
registerDiscordProcessTestLifecycle();
3360

3461
describe("processDiscordMessage ack reactions", () => {
@@ -248,7 +275,7 @@ describe("processDiscordMessage ack reactions", () => {
248275
dispatchInboundMessage.mockResolvedValueOnce({
249276
queuedFinal: false,
250277
counts: { final: 0, tool: 0, block: 0 },
251-
failedCounts: { final: 1 },
278+
settledReceipt: failedFinalReceipt,
252279
});
253280

254281
const ctx = await createAutomaticSourceDeliveryContext();

‎extensions/discord/src/monitor/message-handler.process.test-harness.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,19 @@ const dispatchInboundMessage = vi.hoisted(() =>
232232
queuedFinal: boolean;
233233
counts: { final: number; tool: number; block: number };
234234
failedCounts?: { final?: number; tool?: number; block?: number };
235+
settledReceipt?: {
236+
counts: Record<
237+
"tool" | "block" | "final",
238+
{
239+
delivered: number;
240+
deliveredNotVisible: number;
241+
cancelled: number;
242+
failedBeforeSend: number;
243+
failedAfterSend: number;
244+
}
245+
>;
246+
anyVisibleDelivered: boolean;
247+
};
235248
}>
236249
>(async (_params?: DispatchInboundParams) => ({
237250
queuedFinal: false,
@@ -391,6 +404,7 @@ vi.mock("openclaw/plugin-sdk/reply-runtime", () => ({
391404
await Promise.all(pendingDeliveries);
392405
}),
393406
getQueuedCounts: vi.fn(() => ({ tool: 0, block: 0, final: 0 })),
407+
getFailedCounts: vi.fn(() => ({ tool: 0, block: 0, final: 0 })),
394408
markComplete: vi.fn(),
395409
},
396410
replyOptions: {

‎extensions/discord/src/monitor/message-handler.process.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -565,11 +565,11 @@ async function processDiscordMessageInner(
565565
),
566566
);
567567
};
568-
let dispatchResult: {
569-
queuedFinal: boolean;
570-
counts: Record<ReplyDispatchKind, number>;
571-
failedCounts?: Partial<Record<ReplyDispatchKind, number>>;
572-
} | null = null;
568+
type DispatchResult = Extract<
569+
Awaited<ReturnType<typeof dispatchChannelInboundTurn>>,
570+
{ dispatched: true }
571+
>["dispatchResult"];
572+
let dispatchResult: DispatchResult | null = null;
573573
let dispatchError = false;
574574
let dispatchAborted = false;
575575
const deliverPendingToolWarningFinalIfNeeded = async () => {
@@ -693,7 +693,9 @@ async function processDiscordMessageInner(
693693
endDeliveryCorrelation();
694694
await draftPreview.cleanup();
695695
dispatchError ||= readAgentRunTerminalOutcome(dispatchResult) === "failed";
696-
const finalDeliveryFailed = (dispatchResult?.failedCounts?.final ?? 0) > 0;
696+
const finalReceipt = dispatchResult?.settledReceipt?.counts.final;
697+
const finalDeliveryFailed =
698+
(finalReceipt?.failedBeforeSend ?? 0) + (finalReceipt?.failedAfterSend ?? 0) > 0;
697699
await reactions.finish({ dispatchAborted, dispatchError, finalDeliveryFailed });
698700
}
699701
if (dispatchAborted) {
@@ -705,7 +707,7 @@ async function processDiscordMessageInner(
705707
return;
706708
}
707709
if (shouldLogVerbose()) {
708-
const finalCount = finalDispatchResult.counts.final;
710+
const finalCount = finalDispatchResult.settledReceipt?.counts.final.delivered ?? 0;
709711
logVerbose(
710712
`discord: delivered ${finalCount} reply${finalCount === 1 ? "" : "ies"} to ${replyTarget}`,
711713
);

‎extensions/discord/src/monitor/native-command.plugin-dispatch.test.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,33 @@ import {
3232
} from "./native-command.test-helpers.js";
3333
import { createNoopThreadBindingManager } from "./thread-bindings.manager.js";
3434

35+
const visibleFinalReceipt = {
36+
counts: {
37+
tool: {
38+
delivered: 0,
39+
deliveredNotVisible: 0,
40+
cancelled: 0,
41+
failedBeforeSend: 0,
42+
failedAfterSend: 0,
43+
},
44+
block: {
45+
delivered: 0,
46+
deliveredNotVisible: 0,
47+
cancelled: 0,
48+
failedBeforeSend: 0,
49+
failedAfterSend: 0,
50+
},
51+
final: {
52+
delivered: 1,
53+
deliveredNotVisible: 0,
54+
cancelled: 0,
55+
failedBeforeSend: 0,
56+
failedAfterSend: 0,
57+
},
58+
},
59+
anyVisibleDelivered: true,
60+
} as const;
61+
3562
let createDiscordNativeCommand: typeof import("./native-command.js").createDiscordNativeCommand;
3663
const runtimeModuleMocks = vi.hoisted(() => ({
3764
pluginCommandHandler: vi.fn(),
@@ -1532,12 +1559,13 @@ describe("Discord native plugin command dispatch", () => {
15321559
expect(interaction.reply).not.toHaveBeenCalled();
15331560
});
15341561

1535-
it("does not warn when dispatch reports a queued final without visible counts", async () => {
1562+
it("does not warn when the settled receipt reports a visible final", async () => {
15361563
const cfg = createConfig();
15371564
const interaction = createInteraction();
15381565
runtimeModuleMocks.dispatchReplyWithDispatcher.mockResolvedValue({
15391566
counts: { final: 0, block: 0, tool: 0 },
15401567
queuedFinal: true,
1568+
settledReceipt: visibleFinalReceipt,
15411569
} as never);
15421570
const command = await createNativeCommand(cfg, {
15431571
name: "new",

‎extensions/feishu/src/bot.broadcast.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,33 @@ import type { FeishuMessageProcessingClaim } from "./dedup.js";
1010
import type { FeishuIngressLifecycle } from "./feishu-ingress.js";
1111
import { setFeishuRuntime } from "./runtime.js";
1212

13+
const failedFinalReceipt = {
14+
counts: {
15+
tool: {
16+
delivered: 0,
17+
deliveredNotVisible: 0,
18+
cancelled: 0,
19+
failedBeforeSend: 0,
20+
failedAfterSend: 0,
21+
},
22+
block: {
23+
delivered: 0,
24+
deliveredNotVisible: 0,
25+
cancelled: 0,
26+
failedBeforeSend: 0,
27+
failedAfterSend: 0,
28+
},
29+
final: {
30+
delivered: 0,
31+
deliveredNotVisible: 0,
32+
cancelled: 0,
33+
failedBeforeSend: 1,
34+
failedAfterSend: 0,
35+
},
36+
},
37+
anyVisibleDelivered: false,
38+
} as const;
39+
1340
const {
1441
builtInboundContextCalls,
1542
mockCreateFeishuReplyDispatcher,
@@ -449,7 +476,7 @@ describe("broadcast dispatch", () => {
449476
.mockResolvedValueOnce({
450477
queuedFinal: true,
451478
counts: { final: 1 },
452-
failedCounts: { tool: 0, block: 0, final: 1 },
479+
settledReceipt: failedFinalReceipt,
453480
});
454481
const ensureNoVisibleReplyFallback = vi.fn();
455482
mockCreateFeishuReplyDispatcher.mockReturnValueOnce({

‎extensions/feishu/src/bot.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,33 @@ import { createFeishuMessageReceiveHandler } from "./monitor.message-handler.js"
2424
import { setFeishuRuntime } from "./runtime.js";
2525
import { setFeishuSyntheticDirectPreDispatchTarget } from "./synthetic-event-target.js";
2626

27+
const failedFinalReceipt = {
28+
counts: {
29+
tool: {
30+
delivered: 0,
31+
deliveredNotVisible: 0,
32+
cancelled: 0,
33+
failedBeforeSend: 0,
34+
failedAfterSend: 0,
35+
},
36+
block: {
37+
delivered: 0,
38+
deliveredNotVisible: 0,
39+
cancelled: 0,
40+
failedBeforeSend: 0,
41+
failedAfterSend: 0,
42+
},
43+
final: {
44+
delivered: 0,
45+
deliveredNotVisible: 0,
46+
cancelled: 0,
47+
failedBeforeSend: 1,
48+
failedAfterSend: 0,
49+
},
50+
},
51+
anyVisibleDelivered: false,
52+
} as const;
53+
2754
type ConfiguredBindingRoute = ReturnType<typeof resolveConfiguredBindingRoute>;
2855
type BoundConversation = ReturnType<
2956
ReturnType<typeof getSessionBindingService>["resolveByConversation"]
@@ -1179,7 +1206,7 @@ describe("handleFeishuMessage command authorization", () => {
11791206
mockDispatchReplyFromConfig.mockResolvedValueOnce({
11801207
queuedFinal: true,
11811208
counts: { tool: 0, block: 0, final: 1 },
1182-
failedCounts: { tool: 0, block: 0, final: 1 },
1209+
settledReceipt: failedFinalReceipt,
11831210
});
11841211
const ensureNoVisibleReplyFallback = vi.fn();
11851212
mockCreateFeishuReplyDispatcher.mockReturnValueOnce({

‎extensions/feishu/src/bot.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -100,24 +100,23 @@ const permissionErrorNotifiedAt = new Map<string, number>();
100100
const PERMISSION_ERROR_COOLDOWN_MS = 5 * 60 * 1000; // 5 minutes
101101

102102
function shouldSendNoVisibleReplyFallback(dispatchResult: {
103-
counts: { final?: number };
104-
failedCounts?: { final?: number };
103+
settledReceipt?: {
104+
anyVisibleDelivered: boolean;
105+
counts: { final: { failedBeforeSend: number } };
106+
};
105107
noVisibleReplyFallbackEligible?: boolean;
106-
queuedFinal?: boolean;
107108
sendPolicyDenied?: boolean;
108109
sourceReplyDeliveryMode?: string;
109110
}): boolean {
110-
const finalCount = dispatchResult.counts.final ?? 0;
111-
const failedFinalCount = dispatchResult.failedCounts?.final ?? 0;
112111
const emptyEligibleDispatch =
113112
dispatchResult.noVisibleReplyFallbackEligible === true &&
114-
dispatchResult.queuedFinal !== true &&
115-
finalCount === 0;
116-
const queuedFinalFailed = dispatchResult.queuedFinal === true && failedFinalCount > 0;
113+
dispatchResult.settledReceipt?.anyVisibleDelivered !== true;
114+
const finalFailedBeforeSend =
115+
(dispatchResult.settledReceipt?.counts.final.failedBeforeSend ?? 0) > 0;
117116
return (
118117
dispatchResult.sendPolicyDenied !== true &&
119118
dispatchResult.sourceReplyDeliveryMode !== "message_tool_only" &&
120-
(emptyEligibleDispatch || queuedFinalFailed)
119+
(emptyEligibleDispatch || finalFailedBeforeSend)
121120
);
122121
}
123122

‎extensions/feishu/src/comment-handler.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Feishu plugin module implements comment handler behavior.
2+
import { resolveInboundReplyDispatchCounts } from "openclaw/plugin-sdk/channel-inbound";
23
import { bindIngressLifecycleToReplyOptions } from "openclaw/plugin-sdk/channel-outbound";
34
import { parseStrictNonNegativeInteger } from "openclaw/plugin-sdk/number-runtime";
45
import type { ResolvedAgentRoute } from "openclaw/plugin-sdk/routing";
@@ -316,11 +317,10 @@ export async function handleFeishuCommentEvent(
316317
},
317318
});
318319
const dispatchResult = turnResult.dispatched ? turnResult.dispatchResult : undefined;
319-
const queuedFinal = dispatchResult?.queuedFinal ?? false;
320-
const counts = dispatchResult?.counts ?? { tool: 0, block: 0, final: 0 };
320+
const counts = resolveInboundReplyDispatchCounts(dispatchResult);
321321
log(
322322
`feishu[${account.accountId}]: drive comment dispatch complete ` +
323-
`(queuedFinal=${queuedFinal}, replies=${counts.final}, session=${commentSessionKey})`,
323+
`(replies=${counts.final}, session=${commentSessionKey})`,
324324
);
325325
} finally {
326326
void cleanupTypingReaction();

‎extensions/matrix/src/matrix/monitor/handler.test-helpers.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,19 @@ type MatrixDispatchInboundMessage = (params: {
2525
}) => Promise<{
2626
queuedFinal: boolean;
2727
counts: { final: number; block: number; tool: number };
28+
settledReceipt?: {
29+
anyVisibleDelivered: boolean;
30+
counts: Record<
31+
"tool" | "block" | "final",
32+
{
33+
delivered: number;
34+
deliveredNotVisible: number;
35+
cancelled: number;
36+
failedBeforeSend: number;
37+
failedAfterSend: number;
38+
}
39+
>;
40+
};
2841
}>;
2942

3043
const DEFAULT_ROUTE = {

‎extensions/matrix/src/matrix/monitor/handler.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,55 @@ describe("matrix monitor handler pairing account scope", () => {
323323
);
324324
});
325325

326+
it("logs final delivery from the settled receipt instead of legacy counters", async () => {
327+
const logVerboseMessage = vi.fn();
328+
const { handler } = createMatrixHandlerTestHarness({
329+
logVerboseMessage,
330+
dispatchInboundMessage: async () => ({
331+
queuedFinal: false,
332+
counts: { final: 0, block: 0, tool: 0 },
333+
settledReceipt: {
334+
anyVisibleDelivered: true,
335+
counts: {
336+
tool: {
337+
delivered: 0,
338+
deliveredNotVisible: 0,
339+
cancelled: 0,
340+
failedBeforeSend: 0,
341+
failedAfterSend: 0,
342+
},
343+
block: {
344+
delivered: 0,
345+
deliveredNotVisible: 0,
346+
cancelled: 0,
347+
failedBeforeSend: 0,
348+
failedAfterSend: 0,
349+
},
350+
final: {
351+
delivered: 1,
352+
deliveredNotVisible: 0,
353+
cancelled: 0,
354+
failedBeforeSend: 0,
355+
failedAfterSend: 0,
356+
},
357+
},
358+
},
359+
}),
360+
});
361+
362+
await handler(
363+
"!room:example.org",
364+
createMatrixTextMessageEvent({
365+
eventId: "$settled-final",
366+
body: "hello",
367+
}),
368+
);
369+
370+
expect(logVerboseMessage).toHaveBeenCalledWith(
371+
expect.stringMatching(/^matrix: delivered 1 reply to /),
372+
);
373+
});
374+
326375
it("caches account-scoped allowFrom store reads on hot path", async () => {
327376
const readAllowFromStore = vi.fn(async () => [] as string[]);
328377
sendMessageMatrixMock.mockClear();

0 commit comments

Comments
 (0)