Skip to content

Commit 97034f3

Browse files
steipetePeter Steinberger
andauthored
fix(telegram): recover directed turns after empty model replies (#118305)
* fix(telegram): recover empty directed replies * test: fix empty-reply assertions * test: restore result assertions --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent afdb411 commit 97034f3

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
@@ -1752,7 +1752,7 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
17521752
expectNoWarnMessageWith("settled post-tool turn lacked a final answer");
17531753
});
17541754

1755-
it("returns NO_REPLY without retrying reasoning-only assistant turns when silence is allowed", async () => {
1755+
it("retries reasoning-only assistant turns even when deliberate silence is allowed", async () => {
17561756
mockedClassifyFailoverReason.mockReturnValue(null);
17571757
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
17581758
makeAttemptResult({
@@ -1772,23 +1772,30 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
17721772
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
17731773
}),
17741774
);
1775+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
1776+
makeAttemptResult({
1777+
assistantTexts: ["Visible answer."],
1778+
lastAssistant: {
1779+
role: "assistant",
1780+
stopReason: "end_turn",
1781+
provider: "openai",
1782+
model: "gpt-5.5",
1783+
content: [{ type: "text", text: "Visible answer." }],
1784+
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
1785+
}),
1786+
);
17751787

1776-
const result = await runEmbeddedAgent({
1788+
await runEmbeddedAgent({
17771789
...overflowBaseRunParams,
17781790
allowEmptyAssistantReplyAsSilent: true,
17791791
provider: "openai",
17801792
model: "gpt-5.5",
17811793
runId: "run-reasoning-only-silent",
17821794
});
17831795

1784-
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
1785-
const onlyCall = runAttemptCall(0);
1786-
expect(onlyCall.prompt).not.toContain(REASONING_ONLY_RETRY_INSTRUCTION);
1787-
expect(onlyCall.prompt).not.toContain(EMPTY_RESPONSE_RETRY_INSTRUCTION);
1788-
expectNoWarnMessageWith("reasoning-only assistant turn detected");
1789-
expect(result.payloads).toEqual([{ text: "NO_REPLY" }]);
1790-
expect(result.meta.terminalReplyKind).toBe("silent-empty");
1791-
expect(result.meta.livenessState).toBe("working");
1796+
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(2);
1797+
expect(runAttemptCall(1).prompt).toBe(REASONING_ONLY_RETRY_INSTRUCTION);
1798+
expectWarnMessageWith("reasoning-only assistant turn detected");
17921799
});
17931800

17941801
it("replays an unpersisted reasoning continuation across a missing-assistant retry", async () => {
@@ -4618,7 +4625,7 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
46184625
expect(retryInstruction).toBe(EMPTY_RESPONSE_RETRY_INSTRUCTION);
46194626
});
46204627

4621-
it("treats clean empty assistant turns as silent only when the caller allows it", () => {
4628+
it("treats clean empty assistant turns as silent only for reply-optional runs", () => {
46224629
const attempt = makeAttemptResult({
46234630
assistantTexts: [],
46244631
lastAssistant: {
@@ -4638,6 +4645,16 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
46384645
timedOut: false,
46394646
attempt,
46404647
}),
4648+
).toBe(false);
4649+
expect(
4650+
shouldTreatEmptyAssistantReplyAsSilent({
4651+
allowEmptyAssistantReplyAsSilent: true,
4652+
terminalReplyExpectation: "optional",
4653+
payloadCount: 0,
4654+
aborted: false,
4655+
timedOut: false,
4656+
attempt,
4657+
}),
46414658
).toBe(true);
46424659
expect(
46434660
shouldTreatEmptyAssistantReplyAsSilent({
@@ -4650,7 +4667,7 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
46504667
).toBe(false);
46514668
});
46524669

4653-
it("treats reasoning-only assistant turns as silent only when the caller allows it", () => {
4670+
it("treats reasoning-only assistant turns as silent only for reply-optional runs", () => {
46544671
const attempt = makeAttemptResult({
46554672
assistantTexts: [],
46564673
lastAssistant: {
@@ -4676,6 +4693,16 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
46764693
timedOut: false,
46774694
attempt,
46784695
}),
4696+
).toBe(false);
4697+
expect(
4698+
shouldTreatEmptyAssistantReplyAsSilent({
4699+
allowEmptyAssistantReplyAsSilent: true,
4700+
terminalReplyExpectation: "optional",
4701+
payloadCount: 0,
4702+
aborted: false,
4703+
timedOut: false,
4704+
attempt,
4705+
}),
46794706
).toBe(true);
46804707
expect(
46814708
shouldTreatEmptyAssistantReplyAsSilent({
@@ -4828,9 +4855,9 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
48284855
).toBe(false);
48294856
});
48304857

4831-
it("returns NO_REPLY without retrying clean empty assistant turns when silence is allowed", async () => {
4858+
it("retries clean empty assistant turns even when deliberate silence is allowed", async () => {
48324859
mockedClassifyFailoverReason.mockReturnValue(null);
4833-
mockedRunEmbeddedAttempt.mockResolvedValue(
4860+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
48344861
makeAttemptResult({
48354862
assistantTexts: [],
48364863
lastAssistant: {
@@ -4842,22 +4869,30 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
48424869
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
48434870
}),
48444871
);
4872+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
4873+
makeAttemptResult({
4874+
assistantTexts: ["Visible answer."],
4875+
lastAssistant: {
4876+
role: "assistant",
4877+
stopReason: "stop",
4878+
provider: "openai",
4879+
model: "gpt-5.5",
4880+
content: [{ type: "text", text: "Visible answer." }],
4881+
} as unknown as EmbeddedRunAttemptResult["lastAssistant"],
4882+
}),
4883+
);
48454884

4846-
const result = await runEmbeddedAgent({
4885+
await runEmbeddedAgent({
48474886
...overflowBaseRunParams,
48484887
allowEmptyAssistantReplyAsSilent: true,
48494888
provider: "openai",
48504889
model: "gpt-5.5",
48514890
runId: "run-empty-assistant-silent",
48524891
});
48534892

4854-
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(1);
4855-
const onlyCall = runAttemptCall(0);
4856-
expect(onlyCall.prompt).not.toContain(REASONING_ONLY_RETRY_INSTRUCTION);
4857-
expect(onlyCall.prompt).not.toContain(EMPTY_RESPONSE_RETRY_INSTRUCTION);
4858-
expect(result.payloads).toEqual([{ text: "NO_REPLY" }]);
4859-
expect(result.meta.terminalReplyKind).toBe("silent-empty");
4860-
expect(result.meta.livenessState).toBe("working");
4893+
expect(mockedRunEmbeddedAttempt).toHaveBeenCalledTimes(2);
4894+
expect(runAttemptCall(1).prompt).toBe(EMPTY_RESPONSE_RETRY_INSTRUCTION);
4895+
expectWarnMessageWith("empty response detected");
48614896
});
48624897

48634898
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)