Skip to content

Commit 430fca6

Browse files
fix(reply): preserve streamed Telegram replies on failure
Preserve already-visible Telegram partial replies when a later run failure occurs. Finalize the same draft with the terminal notice while keeping the reply operation in run_failed state. Co-authored-by: Dinesh Suthar <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 29113f7 commit 430fca6

9 files changed

Lines changed: 362 additions & 14 deletions

‎extensions/telegram/src/bot-message-dispatch.draft-failures-progress.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { dispatchReplyWithBufferedBlockDispatcher as dispatchReplyWithBufferedBlockDispatcherRuntime } from "openclaw/plugin-sdk/reply-dispatch-runtime";
12
import { expect, it, vi } from "vitest";
23
import {
34
describeTelegramDispatch,
@@ -78,6 +79,49 @@ describeTelegramDispatch("dispatchTelegramMessage draft-failures-progress", () =
7879
);
7980
});
8081

82+
it.each([
83+
{ label: "direct chat", createSessionPayload: createDirectSessionPayload },
84+
{
85+
label: "group chat",
86+
createSessionPayload: () => ({
87+
...createDirectSessionPayload(),
88+
SessionKey: "agent:test:telegram:group:-100123",
89+
ChatType: "group" as const,
90+
}),
91+
},
92+
])(
93+
"finalizes the default streamed draft in place after an unexpected reply failure in a $label",
94+
async ({ createSessionPayload }) => {
95+
const { answerDraftStream } = setupDraftStreams({ answerMessageId: 2001 });
96+
dispatchReplyWithBufferedBlockDispatcher.mockImplementation(async (params) => {
97+
expect(params.replyOptions?.disableBlockStreaming).toBe(true);
98+
return await dispatchReplyWithBufferedBlockDispatcherRuntime({
99+
...params,
100+
replyResolver: async (_ctx, opts) => {
101+
await opts?.onPartialReply?.({ text: "partial answer" });
102+
throw new Error("unexpected model failure");
103+
},
104+
});
105+
});
106+
107+
await dispatchWithContext({
108+
context: createContext({ ctxPayload: createSessionPayload() }),
109+
streamMode: "partial",
110+
telegramCfg: { streaming: { mode: "partial" } },
111+
});
112+
113+
expect(answerDraftStream.update).toHaveBeenNthCalledWith(1, "partial answer");
114+
expect(answerDraftStream.update).toHaveBeenCalledTimes(2);
115+
expect(answerDraftStream.update).toHaveBeenLastCalledWith(
116+
expect.stringMatching(
117+
/^partial answer\n\n.*Something went wrong while processing your request\. Please try again, or use \/new to start a fresh session\.$/,
118+
),
119+
);
120+
expect(answerDraftStream.clear).not.toHaveBeenCalled();
121+
expect(deliverReplies).not.toHaveBeenCalled();
122+
},
123+
);
124+
81125
it("returns retryable when dispatch fails after partial output and the fallback is not delivered", async () => {
82126
deliverReplies.mockResolvedValueOnce({ delivered: true });
83127
deliverReplies.mockResolvedValueOnce({ delivered: false });

‎extensions/telegram/src/lane-delivery-text-deliverer.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -275,9 +275,10 @@ export function createLaneTextDeliverer(params: CreateLaneTextDelivererParams) {
275275
buttons: TelegramInlineButtons | undefined,
276276
promptContextSequence: TelegramPromptContextProjectionSequence,
277277
followedByDurablePayload = false,
278+
allowErrorPayload = false,
278279
): Promise<LaneDeliveryResult | undefined> => {
279280
const stream = lane.stream;
280-
if (!stream || text.length === 0 || payload.isError) {
281+
if (!stream || text.length === 0 || (payload.isError && !allowErrorPayload)) {
281282
return undefined;
282283
}
283284
rotateFinalizedStream(lane);
@@ -390,17 +391,40 @@ export function createLaneTextDeliverer(params: CreateLaneTextDelivererParams) {
390391
const isDurableFinal = infoKind === "final";
391392
const finalizePreview = requestedFinalizePreview ?? isDurableFinal;
392393
const durable = requestedDurable ?? isDurableFinal;
394+
const streamedErrorDraftText =
395+
isDurableFinal &&
396+
payload.isError === true &&
397+
laneName === "answer" &&
398+
lane.stream &&
399+
lane.hasStreamedMessage &&
400+
!lane.finalized &&
401+
!reply.hasMedia &&
402+
text.trim()
403+
? (() => {
404+
const existing = (
405+
lane.lastPartialText ||
406+
lane.stream?.lastDeliveredText?.() ||
407+
""
408+
).trimEnd();
409+
const notice = text.trim();
410+
return existing && !existing.endsWith(notice)
411+
? `${existing}\n\n${notice}`
412+
: existing || notice;
413+
})()
414+
: undefined;
393415
const streamed =
394416
allowStream && !reply.hasMedia
395417
? await streamText(
396418
laneName,
397419
lane,
398-
text,
420+
streamedErrorDraftText ?? text,
399421
payload,
400422
isDurableFinal,
401423
finalizePreview,
402424
buttons,
403425
promptContextSequence,
426+
false,
427+
streamedErrorDraftText !== undefined,
404428
)
405429
: undefined;
406430
if (streamed) {

‎src/auto-reply/reply/agent-runner-core.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@ import type { TemplateContext } from "../templating.js";
3030
import type { VerboseLevel } from "../thinking.js";
3131
import { SILENT_REPLY_TOKEN } from "../tokens.js";
3232
import type { GetReplyOptions, ReplyPayload } from "../types.js";
33-
import { buildKnownAgentRunFailureReplyPayload } from "./agent-runner-failure-reply.js";
33+
import {
34+
buildKnownAgentRunFailureReplyPayload,
35+
buildTerminalAgentRunFailureReplyPayload,
36+
} from "./agent-runner-failure-reply.js";
3437
import type { BlockReplyPipeline } from "./block-reply-pipeline.js";
3538
import { resolveEffectiveReplyRoute } from "./effective-reply-route.js";
3639
import type { InternalGetReplyOptions } from "./get-reply.types.js";
@@ -365,6 +368,9 @@ export async function handleReplyAgentRunError(
365368
error: unknown,
366369
context: {
367370
cfg: OpenClawConfig;
371+
blockReplyPipeline: BlockReplyPipeline | null;
372+
didDeliverVisiblePartialReply: () => boolean;
373+
isHeartbeat: boolean;
368374
isRestartRecoveryArmed: () => boolean;
369375
replyOperation: ReplyOperation;
370376
resolvedVerboseLevel: VerboseLevel;
@@ -374,6 +380,9 @@ export async function handleReplyAgentRunError(
374380
): Promise<ReplyPayload | undefined> {
375381
const {
376382
cfg,
383+
blockReplyPipeline,
384+
didDeliverVisiblePartialReply,
385+
isHeartbeat,
377386
isRestartRecoveryArmed,
378387
replyOperation,
379388
resolvedVerboseLevel,
@@ -426,6 +435,28 @@ export async function handleReplyAgentRunError(
426435
replyOperation.fail("run_failed", error);
427436
return returnWithQueuedFollowupDrain(knownFailurePayload);
428437
}
438+
if (blockReplyPipeline) {
439+
try {
440+
await blockReplyPipeline.flush({ force: true });
441+
} catch (flushError) {
442+
logVerbose(
443+
`failed to flush streamed reply blocks before surfacing run failure: ${String(flushError)}`,
444+
);
445+
}
446+
}
447+
const didDeliverVisibleReply =
448+
(blockReplyPipeline?.didStreamTerminalReply?.() === true && !blockReplyPipeline.isAborted()) ||
449+
didDeliverVisiblePartialReply();
450+
if (!isHeartbeat && didDeliverVisibleReply && !replyOperation.abortSignal.aborted) {
451+
replyOperation.fail("run_failed", error);
452+
return returnWithQueuedFollowupDrain(
453+
buildTerminalAgentRunFailureReplyPayload({
454+
visibleReplyDelivered: true,
455+
sessionCtx,
456+
cfg,
457+
}),
458+
);
459+
}
429460
replyOperation.fail("run_failed", error);
430461
// Keep the followup queue moving even when an unexpected exception escapes
431462
// the run path; the caller still receives the original error.

‎src/auto-reply/reply/agent-runner-execution.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,7 @@ async function executeAgentTurnInternalWithRetryState(
446446
const terminalFailurePayload = terminalRunFailed
447447
? buildTerminalAgentRunFailureReplyPayload({
448448
isHeartbeat: params.isHeartbeat,
449+
visibleReplyDelivered: false,
449450
sessionCtx: params.sessionCtx,
450451
cfg: params.followupRun.run.config,
451452
})

‎src/auto-reply/reply/agent-runner-failure-reply.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -471,18 +471,24 @@ export function markAgentRunFailureReplyPayload<T extends ReplyPayload>(payload:
471471

472472
export function buildTerminalAgentRunFailureReplyPayload(params: {
473473
isHeartbeat?: boolean;
474+
visibleReplyDelivered: boolean;
474475
sessionCtx: ExternalFailureConversationContext;
475476
cfg?: OpenClawConfig;
476477
}): ReplyPayload {
478+
const text = params.isHeartbeat
479+
? HEARTBEAT_EXTERNAL_RUN_FAILURE_TEXT
480+
: GENERIC_EXTERNAL_RUN_FAILURE_TEXT;
481+
// Once output is visible, hiding its terminal failure leaves a misleading partial reply.
482+
// Keep normal group silence only for failures that produced no visible output.
477483
return markAgentRunFailureReplyPayload({
478-
text: resolveExternalRunFailureTextForConversation({
479-
text: params.isHeartbeat
480-
? HEARTBEAT_EXTERNAL_RUN_FAILURE_TEXT
481-
: GENERIC_EXTERNAL_RUN_FAILURE_TEXT,
482-
sessionCtx: params.sessionCtx,
483-
isGenericRunnerFailure: true,
484-
cfg: params.cfg,
485-
}),
484+
text: params.visibleReplyDelivered
485+
? text
486+
: resolveExternalRunFailureTextForConversation({
487+
text,
488+
sessionCtx: params.sessionCtx,
489+
isGenericRunnerFailure: true,
490+
cfg: params.cfg,
491+
}),
486492
});
487493
}
488494

‎src/auto-reply/reply/agent-runner-run.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { hasRestartRecoverySourceClaim } from "../../config/sessions/restart-rec
1010
import { loadSessionEntry, updateSessionEntry } from "../../config/sessions/session-accessor.js";
1111
import { logVerbose } from "../../globals.js";
1212
import { measureDiagnosticsTimelineSpan } from "../../infra/diagnostics-timeline.js";
13+
import { hasOutboundReplyContent } from "../../plugin-sdk/reply-payload.js";
1314
import {
1415
buildHandledBeforeAgentReplyPayloads,
1516
runBeforeAgentReplyForTurn,
@@ -111,6 +112,18 @@ export async function runReplyAgent(
111112
const activeRunQueueMode = effectiveResetTriggered ? "interrupt" : resolvedQueue.mode;
112113

113114
const isHeartbeat = opts?.isHeartbeat === true;
115+
let didDeliverVisiblePartialReply = false;
116+
const runOpts = opts?.onPartialReply
117+
? {
118+
...opts,
119+
onPartialReply: async (payload: Parameters<NonNullable<typeof opts.onPartialReply>>[0]) => {
120+
await opts.onPartialReply?.(payload);
121+
if (hasOutboundReplyContent(payload, { trimText: true })) {
122+
didDeliverVisiblePartialReply = true;
123+
}
124+
},
125+
}
126+
: opts;
114127
const replyOperationRunState = resolveReplyOperationRunState(opts);
115128
const traceAttributes = {
116129
provider: followupRun.run.provider,
@@ -654,7 +667,7 @@ export async function runReplyAgent(
654667
getActiveSessionEntry: () => activeSessionEntry,
655668
isHeartbeat,
656669
isRestartRecoveryArmed,
657-
opts,
670+
opts: runOpts,
658671
pendingToolTasks,
659672
performSessionReset: resetSession,
660673
queueKey,
@@ -694,7 +707,10 @@ export async function runReplyAgent(
694707
});
695708
} catch (error) {
696709
return await handleReplyAgentRunError(error, {
710+
blockReplyPipeline,
697711
cfg,
712+
didDeliverVisiblePartialReply: () => didDeliverVisiblePartialReply,
713+
isHeartbeat,
698714
isRestartRecoveryArmed,
699715
replyOperation,
700716
resolvedVerboseLevel,

0 commit comments

Comments
 (0)