Skip to content

Commit 863beaf

Browse files
committed
fix(telegram): require confirmed final delivery
1 parent 33f5c0b commit 863beaf

16 files changed

Lines changed: 343 additions & 42 deletions

‎extensions/telegram/src/bot-message-dispatch-reply.ts‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -72,17 +72,19 @@ export function createTelegramReplyDelivery(params: {
7272
noteDelivered: () => reasoningStepState.noteReasoningDelivered(),
7373
});
7474

75-
const flushBufferedFinalAnswer = async () => {
75+
const flushBufferedFinalAnswer = async (): Promise<boolean> => {
7676
const buffered = reasoningStepState.takeBufferedFinalAnswer(params.fence.generation());
7777
if (!buffered) {
78-
return;
78+
return false;
7979
}
80-
await params.delivery.deliverFinalAnswerText(
80+
params.state.attemptedVisibleFinalDelivery = true;
81+
const result = await params.delivery.deliverFinalAnswerText(
8182
buffered.payload,
8283
buffered.text,
8384
resolvePayloadTelegramInlineButtons(buffered.payload),
8485
);
8586
reasoningStepState.resetForNextStep();
87+
return result.kind !== "skipped";
8688
};
8789
const trackBlockMedia = (delivered: boolean, kind: string, payload: ReplyPayload) => {
8890
if (delivered && kind === "block" && payload.mediaUrls?.length) {
@@ -94,18 +96,18 @@ export function createTelegramReplyDelivery(params: {
9496

9597
const deliver: Deliver = async (payload, info) => {
9698
if (params.fence.isSuperseded()) {
97-
return;
99+
return false;
98100
}
99101
const normalizedPayload = params.delivery.normalizeDeliveryPayload(payload);
100102
if (!normalizedPayload) {
101-
return;
103+
return false;
102104
}
103105
const deduped =
104106
info.kind === "final"
105107
? deduplicateBlockSentMedia(normalizedPayload, sentBlockMediaUrls)
106108
: normalizedPayload;
107109
if (!deduped) {
108-
return;
110+
return false;
109111
}
110112
const effectivePayload = deduped;
111113
if (
@@ -116,7 +118,7 @@ export function createTelegramReplyDelivery(params: {
116118
})
117119
) {
118120
params.state.queuedFinal = true;
119-
return;
121+
return false;
120122
}
121123
const telegramButtons = resolvePayloadTelegramInlineButtons(effectivePayload);
122124
const lanePayload =
@@ -151,7 +153,7 @@ export function createTelegramReplyDelivery(params: {
151153
!reply.hasMedia &&
152154
!hasExecApprovalPayload(effectivePayload)
153155
) {
154-
return;
156+
return false;
155157
}
156158
if (payload.isError === true) {
157159
params.state.hadErrorReplyFailureOrSkip = true;
@@ -264,11 +266,14 @@ export function createTelegramReplyDelivery(params: {
264266
}
265267
const result =
266268
segment.lane === "answer" && info.kind === "final"
267-
? await params.delivery.deliverFinalAnswerText(
268-
effectivePayload,
269-
segment.update.text,
270-
telegramButtons,
271-
)
269+
? await (async () => {
270+
params.state.attemptedVisibleFinalDelivery = true;
271+
return await params.delivery.deliverFinalAnswerText(
272+
effectivePayload,
273+
segment.update.text,
274+
telegramButtons,
275+
);
276+
})()
272277
: await params.delivery.deliverLaneText({
273278
laneName: segment.lane,
274279
text: segment.update.text,
@@ -294,21 +299,22 @@ export function createTelegramReplyDelivery(params: {
294299
if (segment.lane === "reasoning") {
295300
if (result.kind !== "skipped") {
296301
reasoningStepState.noteReasoningDelivered();
297-
await flushBufferedFinalAnswer();
302+
blockDelivered = (await flushBufferedFinalAnswer()) || blockDelivered;
298303
}
299304
} else if (info.kind === "final") {
300305
reasoningStepState.resetForNextStep();
301306
}
302307
}
303308
if (segments.length > 0) {
304309
trackBlockMedia(blockDelivered, info.kind, effectivePayload);
305-
return;
310+
return blockDelivered;
306311
}
307312

308313
if (split.suppressedReasoningOnly) {
309314
let delivered = false;
310315
if (reply.hasMedia) {
311316
if (info.kind === "final") {
317+
params.state.attemptedVisibleFinalDelivery = true;
312318
await params.draft.rotateAnswerLaneAfterToolProgress();
313319
await params.draft.answerLane.stream?.stop();
314320
await params.draft.reasoningLane.stream?.stop();
@@ -329,7 +335,7 @@ export function createTelegramReplyDelivery(params: {
329335
await flushBufferedFinalAnswer();
330336
}
331337
trackBlockMedia(delivered, info.kind, effectivePayload);
332-
return;
338+
return delivered;
333339
}
334340

335341
if (info.kind === "final") {
@@ -342,7 +348,10 @@ export function createTelegramReplyDelivery(params: {
342348
if (info.kind === "final") {
343349
await flushBufferedFinalAnswer();
344350
}
345-
return;
351+
return false;
352+
}
353+
if (info.kind === "final") {
354+
params.state.attemptedVisibleFinalDelivery = true;
346355
}
347356
const delivered = await params.delivery.sendPayload(effectivePayload, {
348357
durable: info.kind === "final",
@@ -354,6 +363,7 @@ export function createTelegramReplyDelivery(params: {
354363
await flushBufferedFinalAnswer();
355364
}
356365
trackBlockMedia(delivered, info.kind, effectivePayload);
366+
return delivered;
357367
};
358368

359369
const onSkip: Skip = (payload, info) => {

‎extensions/telegram/src/bot-message-dispatch-turn.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,9 @@ export async function runTelegramDispatchTurn(params: {
267267
return false;
268268
}
269269
params.state.queuedFinal = turnResult.dispatchResult.queuedFinal;
270+
if (turnResult.dispatchResult.attemptedVisibleFinalDelivery === true) {
271+
params.state.attemptedVisibleFinalDelivery = true;
272+
}
270273
if ((turnResult.dispatchResult.counts?.final ?? 0) > 0) {
271274
params.progress.markSawFinal();
272275
}

‎extensions/telegram/src/bot-message-dispatch.delivery-basics.test.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -596,4 +596,104 @@ describeTelegramDispatch("dispatchTelegramMessage delivery-basics", () => {
596596
}
597597
},
598598
);
599+
600+
it("sends a fallback when Telegram does not confirm final delivery", async () => {
601+
deliverReplies.mockResolvedValueOnce({ delivered: false }).mockResolvedValueOnce({
602+
delivered: true,
603+
});
604+
dispatchReplyWithBufferedBlockDispatcher.mockImplementation(async ({ dispatcherOptions }) => {
605+
await dispatcherOptions.deliver({ text: "Final answer" }, { kind: "final" });
606+
return { queuedFinal: false, counts: { block: 0, final: 1, tool: 0 } };
607+
});
608+
609+
await dispatchWithContext({
610+
context: createContext({
611+
ctxPayload: {
612+
SessionKey: "agent:default:telegram:direct:123",
613+
ChatType: "direct",
614+
} as unknown as TelegramMessageContext["ctxPayload"],
615+
}),
616+
streamMode: "off",
617+
telegramDeps: telegramDepsForTest,
618+
});
619+
620+
expect(deliverReplies).toHaveBeenCalledTimes(2);
621+
const attemptedFinal = expectRecordFields(mockCallArg(deliverReplies, 0), {});
622+
expectRecordFields((attemptedFinal.replies as Array<Record<string, unknown>>)[0], {
623+
text: "Final answer",
624+
});
625+
const fallback = expectRecordFields(mockCallArg(deliverReplies, 1), {});
626+
expectRecordFields((fallback.replies as Array<Record<string, unknown>>)[0], {
627+
text: "I generated a reply, but Telegram did not confirm delivery. Please try again.",
628+
});
629+
});
630+
631+
it("sends a fallback when routed dispatch reports unconfirmed visible final delivery", async () => {
632+
dispatchReplyWithBufferedBlockDispatcher.mockResolvedValue({
633+
queuedFinal: false,
634+
counts: { block: 0, final: 0, tool: 0 },
635+
attemptedVisibleFinalDelivery: true,
636+
});
637+
638+
await dispatchWithContext({
639+
context: createContext({
640+
ctxPayload: {
641+
SessionKey: "agent:default:telegram:direct:123",
642+
ChatType: "direct",
643+
} as unknown as TelegramMessageContext["ctxPayload"],
644+
}),
645+
streamMode: "off",
646+
telegramDeps: telegramDepsForTest,
647+
});
648+
649+
expect(deliverReplies).toHaveBeenCalledTimes(1);
650+
const fallback = expectRecordFields(mockCallArg(deliverReplies), {});
651+
expectRecordFields((fallback.replies as Array<Record<string, unknown>>)[0], {
652+
text: "I generated a reply, but Telegram did not confirm delivery. Please try again.",
653+
});
654+
});
655+
656+
it("keeps silent direct turns silent when no visible final delivery was attempted", async () => {
657+
dispatchReplyWithBufferedBlockDispatcher.mockResolvedValue({
658+
queuedFinal: false,
659+
counts: { block: 0, final: 0, tool: 0 },
660+
});
661+
662+
await dispatchWithContext({
663+
context: createContext({
664+
ctxPayload: {
665+
SessionKey: "agent:default:telegram:direct:123",
666+
ChatType: "direct",
667+
} as unknown as TelegramMessageContext["ctxPayload"],
668+
}),
669+
streamMode: "off",
670+
telegramDeps: telegramDepsForTest,
671+
});
672+
673+
expect(deliverReplies).not.toHaveBeenCalled();
674+
});
675+
676+
it("returns retryable when unconfirmed final delivery fallback is suppressed", async () => {
677+
deliverReplies.mockResolvedValueOnce({ delivered: false });
678+
dispatchReplyWithBufferedBlockDispatcher.mockImplementation(async ({ dispatcherOptions }) => {
679+
await dispatcherOptions.deliver({ text: "Final answer" }, { kind: "final" });
680+
return { queuedFinal: false, counts: { block: 0, final: 1, tool: 0 } };
681+
});
682+
683+
const result = await dispatchWithContext({
684+
context: createContext({
685+
ctxPayload: {
686+
SessionKey: "agent:default:telegram:direct:123",
687+
ChatType: "direct",
688+
} as unknown as TelegramMessageContext["ctxPayload"],
689+
}),
690+
streamMode: "off",
691+
telegramDeps: telegramDepsForTest,
692+
retryDispatchErrors: true,
693+
suppressFailureFallback: true,
694+
});
695+
696+
expect(result.kind).toBe("failed-retryable");
697+
expect(deliverReplies).toHaveBeenCalledTimes(1);
698+
});
599699
});

‎extensions/telegram/src/bot-message-dispatch.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -471,17 +471,25 @@ export const dispatchTelegramMessage = async ({
471471

472472
const deliverySummary = delivery.snapshot();
473473
let sentFallback = false;
474+
const visibleFinalDeliveryWithoutConfirmation =
475+
state.attemptedVisibleFinalDelivery === true &&
476+
!deliverySummary.delivered &&
477+
!progress.finalAnswerDelivered() &&
478+
!state.suppressSilentReplyFallback;
474479
const shouldSendFailureFallback =
475480
!isRoomEvent &&
476481
!suppressFailureFallback &&
477482
!progress.finalAnswerDelivered() &&
478483
(state.dispatchError ||
484+
visibleFinalDeliveryWithoutConfirmation ||
479485
deliverySummary.skippedNonSilent > 0 ||
480486
deliverySummary.failedNonSilent > 0);
481487
if (shouldSendFailureFallback) {
482488
const fallbackText = state.dispatchError
483489
? "Something went wrong while processing your request. Please try again."
484-
: EMPTY_RESPONSE_FALLBACK;
490+
: visibleFinalDeliveryWithoutConfirmation
491+
? "I generated a reply, but Telegram did not confirm delivery. Please try again."
492+
: EMPTY_RESPONSE_FALLBACK;
485493
const result = await delivery.deliverFallback(
486494
[{ text: fallbackText }],
487495
telegramCfg.silentErrorReplies === true &&
@@ -533,7 +541,9 @@ export const dispatchTelegramMessage = async ({
533541
state.queuedFinal;
534542
const deliveryFailureWithoutFinalResponse =
535543
!progress.finalAnswerDelivered() &&
536-
(deliverySummary.skippedNonSilent > 0 || deliverySummary.failedNonSilent > 0);
544+
(visibleFinalDeliveryWithoutConfirmation ||
545+
deliverySummary.skippedNonSilent > 0 ||
546+
deliverySummary.failedNonSilent > 0);
537547
const retryableDispatchFailure =
538548
state.dispatchError ??
539549
(deliveryFailureWithoutFinalResponse

‎extensions/telegram/src/bot-message-dispatch.types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ export type TelegramAnswerBlockDelivery = {
6666

6767
export type TelegramDispatchTurnState = {
6868
queuedFinal: boolean;
69+
attemptedVisibleFinalDelivery?: boolean;
6970
suppressSilentReplyFallback: boolean;
7071
hadErrorReplyFailureOrSkip: boolean;
7172
dispatchError?: unknown;

‎src/auto-reply/reply/dispatch-from-config.abort.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ export function createAbortAwareDispatcher(params: {
8383
}
8484
},
8585
};
86+
if (params.dispatcher.getDeliveredCounts) {
87+
dispatcher.getDeliveredCounts = () => params.dispatcher.getDeliveredCounts!();
88+
}
8689
if (params.dispatcher.getCancelledCounts) {
8790
dispatcher.getCancelledCounts = () => params.dispatcher.getCancelledCounts!();
8891
}

‎src/auto-reply/reply/dispatch-from-config.final-outcome-counts.test.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,36 @@ describe("getDispatcherFinalOutcomeCounts (#89116)", () => {
1414
} as unknown as ReplyDispatcher;
1515

1616
expect(() => getDispatcherFinalOutcomeCounts(dispatcher)).not.toThrow();
17-
expect(getDispatcherFinalOutcomeCounts(dispatcher)).toEqual({ cancelled: 2, failed: 0 });
17+
expect(getDispatcherFinalOutcomeCounts(dispatcher)).toEqual({
18+
delivered: 0,
19+
cancelled: 2,
20+
failed: 0,
21+
});
1822
});
1923

2024
it("returns cancelled: 0 when getCancelledCounts is absent (existing behavior preserved)", () => {
2125
const dispatcher = {
2226
getFailedCounts: () => ({ tool: 0, block: 1, final: 3 }),
2327
} as unknown as ReplyDispatcher;
2428

25-
expect(getDispatcherFinalOutcomeCounts(dispatcher)).toEqual({ cancelled: 0, failed: 3 });
29+
expect(getDispatcherFinalOutcomeCounts(dispatcher)).toEqual({
30+
delivered: 0,
31+
cancelled: 0,
32+
failed: 3,
33+
});
2634
});
2735

2836
it("uses the real final counts when both methods are present", () => {
2937
const dispatcher = {
3038
getCancelledCounts: () => ({ tool: 0, block: 0, final: 1 }),
39+
getDeliveredCounts: () => ({ tool: 0, block: 0, final: 2 }),
3140
getFailedCounts: () => ({ tool: 0, block: 0, final: 5 }),
3241
} as unknown as ReplyDispatcher;
3342

34-
expect(getDispatcherFinalOutcomeCounts(dispatcher)).toEqual({ cancelled: 1, failed: 5 });
43+
expect(getDispatcherFinalOutcomeCounts(dispatcher)).toEqual({
44+
delivered: 2,
45+
cancelled: 1,
46+
failed: 5,
47+
});
3548
});
3649
});

‎src/auto-reply/reply/dispatch-from-config.hooks-and-send-policy.test-utils.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,11 @@ describe("before_dispatch hook", () => {
8686
it("uses canonical hook metadata and shared routed final delivery", async () => {
8787
ttsMocks.state.synthesizeFinalAudio = true;
8888
hookMocks.runner.runBeforeDispatch.mockResolvedValue({ handled: true, text: "Blocked" });
89+
mocks.routeReply.mockResolvedValueOnce({
90+
ok: true,
91+
attemptedDelivery: true,
92+
messageId: "m1",
93+
} as never);
8994
installThreadingTestPlugin({ id: "telegram" });
9095
const dispatcher = createDispatcher();
9196
const ctx = createHookCtx({
@@ -141,6 +146,31 @@ describe("before_dispatch hook", () => {
141146
expect(result.queuedFinal).toBe(true);
142147
});
143148

149+
it("does not mark routed hook-suppressed finals as attempted visible delivery", async () => {
150+
hookMocks.runner.runBeforeDispatch.mockResolvedValue({ handled: true, text: "Blocked" });
151+
mocks.routeReply.mockResolvedValueOnce({
152+
ok: true,
153+
suppressed: true,
154+
reason: "cancelled_by_reply_payload_sending_hook",
155+
} as never);
156+
installThreadingTestPlugin({ id: "telegram" });
157+
const dispatcher = createDispatcher();
158+
const ctx = createHookCtx({
159+
Provider: "slack",
160+
Surface: "slack",
161+
OriginatingChannel: "telegram",
162+
OriginatingTo: "telegram:999",
163+
ChatType: "direct",
164+
});
165+
166+
const result = await dispatchReplyFromConfig({ ctx, cfg: emptyConfig, dispatcher });
167+
168+
expect(dispatcher.sendFinalReply).not.toHaveBeenCalled();
169+
expect(mocks.routeReply).toHaveBeenCalledTimes(1);
170+
expect(result.queuedFinal).toBe(false);
171+
expect(result.attemptedVisibleFinalDelivery).toBeUndefined();
172+
});
173+
144174
it("passes inbound reply metadata to before_dispatch event and context", async () => {
145175
hookMocks.runner.runBeforeDispatch.mockResolvedValue({ handled: true });
146176
const dispatcher = createDispatcher();

0 commit comments

Comments
 (0)