Skip to content

Commit 991bca3

Browse files
author
Peter Steinberger
committed
fix(telegram): recover empty directed replies
1 parent f5637c0 commit 991bca3

6 files changed

Lines changed: 106 additions & 57 deletions

File tree

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,8 @@ export async function runTelegramDispatchTurn(params: {
285285
return false;
286286
}
287287
params.state.queuedFinal = turnResult.dispatchResult.queuedFinal;
288+
params.state.noVisibleReplyFallbackEligible =
289+
turnResult.dispatchResult.noVisibleReplyFallbackEligible === true;
288290
if ((turnResult.dispatchResult.counts?.final ?? 0) > 0) {
289291
params.progress.markSawFinal();
290292
}

‎extensions/telegram/src/bot-message-dispatch.fallback-topic-media.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,42 @@ describeTelegramDispatch("dispatchTelegramMessage fallback-topic-media", () => {
226226
expect(deliverReplies).not.toHaveBeenCalled();
227227
});
228228

229+
it("recovers a directed turn when shared dispatch marks the empty fallback eligible", async () => {
230+
dispatchReplyWithBufferedBlockDispatcher.mockResolvedValue({
231+
queuedFinal: false,
232+
counts: { block: 0, final: 0, tool: 0 },
233+
noVisibleReplyFallbackEligible: true,
234+
});
235+
236+
await dispatchWithContext({
237+
context: createContext({
238+
chatId: -1001234,
239+
isGroup: true,
240+
ctxPayload: {
241+
SessionKey: "agent:test:telegram:group:-1001234",
242+
ChatType: "group",
243+
} as TelegramMessageContext["ctxPayload"],
244+
primaryCtx: {
245+
message: { chat: { id: -1001234, type: "supergroup" } },
246+
} as TelegramMessageContext["primaryCtx"],
247+
msg: {
248+
chat: { id: -1001234, type: "supergroup" },
249+
message_id: 456,
250+
} as TelegramMessageContext["msg"],
251+
threadSpec: { id: undefined, scope: "none" },
252+
replyThreadId: undefined,
253+
}),
254+
streamMode: "off",
255+
});
256+
257+
expect(deliverReplies).toHaveBeenCalledOnce();
258+
expect(deliverReplies).toHaveBeenCalledWith(
259+
expect.objectContaining({
260+
replies: [{ text: "No response generated. Please try again." }],
261+
}),
262+
);
263+
});
264+
229265
describe("non-streaming media dedup", () => {
230266
const finalDeliveryPayload = () => {
231267
for (const [params] of deliverInboundReplyWithMessageSendContext.mock.calls) {

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

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
11
// Telegram plugin module coordinates one inbound message dispatch lifecycle.
2-
import {
3-
createOutboundPayloadPlan,
4-
projectOutboundPayloadPlanForDelivery,
5-
} from "openclaw/plugin-sdk/channel-outbound";
62
import { getGlobalHookRunner } from "openclaw/plugin-sdk/plugin-runtime";
73
import { createSubsystemLogger, danger, logVerbose } from "openclaw/plugin-sdk/runtime-env";
84
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
@@ -384,6 +380,7 @@ export const dispatchTelegramMessage = async ({
384380
});
385381
const state: TelegramDispatchTurnState = {
386382
queuedFinal: false,
383+
noVisibleReplyFallbackEligible: false,
387384
suppressSilentReplyFallback: false,
388385
hadErrorReplyFailureOrSkip: false,
389386
};
@@ -509,25 +506,12 @@ export const dispatchTelegramMessage = async ({
509506
!deliverySummary.delivered &&
510507
!state.suppressSilentReplyFallback &&
511508
!state.queuedFinal &&
512-
dispatchContext.isGroup
509+
state.noVisibleReplyFallbackEligible
513510
) {
514-
const policySessionKey =
515-
dispatchContext.ctxPayload.CommandSource === "native"
516-
? (dispatchContext.ctxPayload.CommandTargetSessionKey ??
517-
dispatchContext.ctxPayload.SessionKey)
518-
: dispatchContext.ctxPayload.SessionKey;
519-
const silentReplyFallback = projectOutboundPayloadPlanForDelivery(
520-
createOutboundPayloadPlan([{ text: "NO_REPLY" }], {
521-
cfg,
522-
sessionKey: policySessionKey,
523-
surface: "telegram",
524-
}),
525-
);
526-
if (silentReplyFallback.length > 0) {
527-
sentFallback = (await delivery.deliverFallback(silentReplyFallback, false)).delivered;
528-
}
529-
silentReplyDispatchLogger.debug("telegram turn ended without visible final response", {
530-
hasSessionKey: Boolean(policySessionKey),
511+
sentFallback = (await delivery.deliverFallback([{ text: EMPTY_RESPONSE_FALLBACK }], false))
512+
.delivered;
513+
silentReplyDispatchLogger.debug("telegram recovered eligible turn without visible response", {
514+
hasSessionKey: Boolean(dispatchContext.ctxPayload.SessionKey),
531515
hasChatId: dispatchContext.chatId != null,
532516
queuedFinal: state.queuedFinal,
533517
sentFallback,

‎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+
noVisibleReplyFallbackEligible: boolean;
6970
suppressSilentReplyFallback: boolean;
7071
hadErrorReplyFailureOrSkip: boolean;
7172
dispatchError?: unknown;

‎src/agents/embedded-agent-runner/run.incomplete-turn.test.ts‎

Lines changed: 57 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
117117
}),
118118
);
119119

120-
const result = await runEmbeddedAgent({
120+
await runEmbeddedAgent({
121121
...overflowBaseRunParams,
122122
runId: "run-tool-summary-failure-count",
123123
});
@@ -1566,7 +1566,7 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
15661566
expectNoWarnMessageWith("settled post-tool turn lacked a final answer");
15671567
});
15681568

1569-
it("returns NO_REPLY without retrying reasoning-only assistant turns when silence is allowed", async () => {
1569+
it("retries reasoning-only assistant turns even when deliberate silence is allowed", async () => {
15701570
mockedClassifyFailoverReason.mockReturnValue(null);
15711571
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
15721572
makeAttemptResult({
@@ -1586,6 +1586,18 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
15861586
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
15871587
}),
15881588
);
1589+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
1590+
makeAttemptResult({
1591+
assistantTexts: ["Visible answer."],
1592+
lastAssistant: {
1593+
role: "assistant",
1594+
stopReason: "end_turn",
1595+
provider: "openai",
1596+
model: "gpt-5.5",
1597+
content: [{ type: "text", text: "Visible answer." }],
1598+
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
1599+
}),
1600+
);
15891601

15901602
const result = await runEmbeddedAgent({
15911603
...overflowBaseRunParams,
@@ -1595,14 +1607,9 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
15951607
runId: "run-reasoning-only-silent",
15961608
});
15971609

1598-
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
1599-
const onlyCall = runAttemptCall(0);
1600-
expect(onlyCall.prompt).not.toContain(REASONING_ONLY_RETRY_INSTRUCTION);
1601-
expect(onlyCall.prompt).not.toContain(EMPTY_RESPONSE_RETRY_INSTRUCTION);
1602-
expectNoWarnMessageWith("reasoning-only assistant turn detected");
1603-
expect(result.payloads).toEqual([{ text: "NO_REPLY" }]);
1604-
expect(result.meta.terminalReplyKind).toBe("silent-empty");
1605-
expect(result.meta.livenessState).toBe("working");
1610+
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(2);
1611+
expect(runAttemptCall(1).prompt).toBe(REASONING_ONLY_RETRY_INSTRUCTION);
1612+
expectWarnMessageWith("reasoning-only assistant turn detected");
16061613
});
16071614

16081615
it("replays an unpersisted reasoning continuation across a missing-assistant retry", async () => {
@@ -1680,7 +1687,7 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
16801687
}),
16811688
);
16821689

1683-
const result = await runEmbeddedAgent({
1690+
await runEmbeddedAgent({
16841691
...overflowBaseRunParams,
16851692
provider: "openai",
16861693
model: "gpt-5.4",
@@ -4243,7 +4250,7 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
42434250
expect(retryInstruction).toBe(EMPTY_RESPONSE_RETRY_INSTRUCTION);
42444251
});
42454252

4246-
it("treats clean empty assistant turns as silent only when the caller allows it", () => {
4253+
it("treats clean empty assistant turns as silent only for reply-optional runs", () => {
42474254
const attempt = makeAttemptResult({
42484255
assistantTexts: [],
42494256
lastAssistant: {
@@ -4263,6 +4270,16 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
42634270
timedOut: false,
42644271
attempt,
42654272
}),
4273+
).toBe(false);
4274+
expect(
4275+
shouldTreatEmptyAssistantReplyAsSilent({
4276+
allowEmptyAssistantReplyAsSilent: true,
4277+
terminalReplyExpectation: "optional",
4278+
payloadCount: 0,
4279+
aborted: false,
4280+
timedOut: false,
4281+
attempt,
4282+
}),
42664283
).toBe(true);
42674284
expect(
42684285
shouldTreatEmptyAssistantReplyAsSilent({
@@ -4275,7 +4292,7 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
42754292
).toBe(false);
42764293
});
42774294

4278-
it("treats reasoning-only assistant turns as silent only when the caller allows it", () => {
4295+
it("treats reasoning-only assistant turns as silent only for reply-optional runs", () => {
42794296
const attempt = makeAttemptResult({
42804297
assistantTexts: [],
42814298
lastAssistant: {
@@ -4301,6 +4318,16 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
43014318
timedOut: false,
43024319
attempt,
43034320
}),
4321+
).toBe(false);
4322+
expect(
4323+
shouldTreatEmptyAssistantReplyAsSilent({
4324+
allowEmptyAssistantReplyAsSilent: true,
4325+
terminalReplyExpectation: "optional",
4326+
payloadCount: 0,
4327+
aborted: false,
4328+
timedOut: false,
4329+
attempt,
4330+
}),
43044331
).toBe(true);
43054332
expect(
43064333
shouldTreatEmptyAssistantReplyAsSilent({
@@ -4453,9 +4480,9 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
44534480
).toBe(false);
44544481
});
44554482

4456-
it("returns NO_REPLY without retrying clean empty assistant turns when silence is allowed", async () => {
4483+
it("retries clean empty assistant turns even when deliberate silence is allowed", async () => {
44574484
mockedClassifyFailoverReason.mockReturnValue(null);
4458-
mockedRunEmbeddedAttempt.mockResolvedValue(
4485+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
44594486
makeAttemptResult({
44604487
assistantTexts: [],
44614488
lastAssistant: {
@@ -4467,6 +4494,18 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
44674494
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
44684495
}),
44694496
);
4497+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
4498+
makeAttemptResult({
4499+
assistantTexts: ["Visible answer."],
4500+
lastAssistant: {
4501+
role: "assistant",
4502+
stopReason: "stop",
4503+
provider: "openai",
4504+
model: "gpt-5.5",
4505+
content: [{ type: "text", text: "Visible answer." }],
4506+
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
4507+
}),
4508+
);
44704509

44714510
const result = await runEmbeddedAgent({
44724511
...overflowBaseRunParams,
@@ -4476,13 +4515,9 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
44764515
runId: "run-empty-assistant-silent",
44774516
});
44784517

4479-
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
4480-
const onlyCall = runAttemptCall(0);
4481-
expect(onlyCall.prompt).not.toContain(REASONING_ONLY_RETRY_INSTRUCTION);
4482-
expect(onlyCall.prompt).not.toContain(EMPTY_RESPONSE_RETRY_INSTRUCTION);
4483-
expect(result.payloads).toEqual([{ text: "NO_REPLY" }]);
4484-
expect(result.meta.terminalReplyKind).toBe("silent-empty");
4485-
expect(result.meta.livenessState).toBe("working");
4518+
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(2);
4519+
expect(runAttemptCall(1).prompt).toBe(EMPTY_RESPONSE_RETRY_INSTRUCTION);
4520+
expectWarnMessageWith("empty response detected");
44864521
});
44874522

44884523
it("returns NO_REPLY without retrying exact silent assistant replies when silence is allowed", async () => {

‎src/agents/embedded-agent-runner/run/incomplete-turn.ts‎

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -700,19 +700,10 @@ export function shouldTreatEmptyAssistantReplyAsSilent(params: {
700700
) {
701701
return true;
702702
}
703-
if (params.onlyExplicitSilentReply) {
704-
return false;
705-
}
706-
// Post-tool empty stops are ambiguous provider failures when a reply is still
707-
// expected; reply-optional runs settle their work in the tools themselves.
708-
if (
709-
!terminalReplyOptional &&
710-
params.attempt.toolMetas.length > 0 &&
711-
isEmptyResponseAssistantTurn({
712-
payloadCount: params.payloadCount,
713-
attempt: params.attempt,
714-
})
715-
) {
703+
// A visible turn owes a reply unless the model explicitly chose NO_REPLY.
704+
// Bare empty and reasoning-only stops are provider failures, even when the
705+
// conversation policy permits deliberate silence.
706+
if (params.onlyExplicitSilentReply || !terminalReplyOptional) {
716707
return false;
717708
}
718709
return isNonVisibleAssistantTurnEligibleForSilentReply({

0 commit comments

Comments
 (0)