Skip to content

Commit 02b8ed7

Browse files
fix(channels/turn): clear pending history on error paths (#123193)
Failed channel turns could leave caller-owned pending group history in the next prompt. Finalize it on every terminal path, and filter Telegram rolling context while preserving explicit reply ancestry. Co-authored-by: SunnyShu0925 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 63afe5e commit 02b8ed7

5 files changed

Lines changed: 283 additions & 119 deletions

File tree

‎extensions/telegram/src/bot-message-context.prompt-context.test.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,80 @@ describe("buildTelegramMessageContext prompt context", () => {
355355
]);
356356
});
357357

358+
it("keeps an explicit reply target while omitting cached context before the latest bot reply", async () => {
359+
const historyKey = "-1001234567890";
360+
const previousUserMessage = {
361+
messageId: "10",
362+
sender: "Pat",
363+
timestamp: 1_700_000_000_000,
364+
body: "failed turn already in the transcript",
365+
};
366+
const previousBotReply = {
367+
messageId: "11",
368+
sender: "OpenClaw (you)",
369+
timestamp: 1_700_000_001_000,
370+
body: "LLM request failed.",
371+
};
372+
const ctx = await buildTelegramMessageContextForTest({
373+
message: {
374+
message_id: 12,
375+
chat: { id: -1001234567890, type: "supergroup", title: "Room" },
376+
from: { id: 1234, first_name: "Pat" },
377+
text: "@bot recover",
378+
entities: [{ type: "mention", offset: 0, length: 4 }],
379+
},
380+
historyLimit: 10,
381+
groupHistories: new Map([[historyKey, [previousUserMessage, previousBotReply]]]),
382+
promptContext: [
383+
{
384+
label: "Conversation context",
385+
source: "telegram",
386+
type: "chat_window",
387+
payload: {
388+
order: "chronological",
389+
relation: "selected_for_current_message",
390+
messages: [
391+
{
392+
message_id: previousUserMessage.messageId,
393+
sender: previousUserMessage.sender,
394+
timestamp_ms: previousUserMessage.timestamp,
395+
body: previousUserMessage.body,
396+
},
397+
{
398+
message_id: previousBotReply.messageId,
399+
sender: previousBotReply.sender,
400+
timestamp_ms: previousBotReply.timestamp,
401+
body: previousBotReply.body,
402+
},
403+
{
404+
message_id: "9",
405+
sender: "OpenClaw (you)",
406+
timestamp_ms: 1_699_999_999_000,
407+
body: "explicit reply target",
408+
is_reply_target: true,
409+
},
410+
],
411+
},
412+
},
413+
],
414+
});
415+
416+
expect(ctx?.ctxPayload.ChannelStructuredContext).toEqual([
417+
expect.objectContaining({
418+
type: "chat_window",
419+
payload: expect.objectContaining({
420+
messages: [
421+
expect.objectContaining({
422+
message_id: "9",
423+
body: "explicit reply target",
424+
is_reply_target: true,
425+
}),
426+
],
427+
}),
428+
}),
429+
]);
430+
});
431+
358432
it("excludes ambient transcript rows from the group history window", async () => {
359433
const ctx = await buildTelegramMessageContextForTest({
360434
message: {

‎extensions/telegram/src/bot-message-context.session.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ import {
6060
isTelegramChatWindowPromptContext,
6161
mergeTelegramGroupHistoryPromptContext,
6262
recordTelegramGroupHistoryEntry,
63+
retainTelegramGroupHistoryPromptContext,
6364
selectTelegramGroupHistoryAfterLastSelf,
6465
} from "./group-history-window.js";
6566
import { TELEGRAM_REPLY_CHAIN_MAX_DEPTH, type TelegramReplyChainEntry } from "./message-cache.js";
@@ -572,8 +573,14 @@ export async function buildTelegramInboundContextPayload(params: {
572573
groupHistoryPromptEntries =
573574
inboundEventKind === "room_event" ? fullGroupHistoryEntries : watermarkedGroupHistoryEntries;
574575
}
576+
const retainedVisiblePromptContext = hasGroupHistoryContext
577+
? retainTelegramGroupHistoryPromptContext({
578+
promptContext: baseVisiblePromptContext,
579+
entries: groupHistoryPromptEntries,
580+
})
581+
: baseVisiblePromptContext;
575582
const visiblePromptContext = mergeTelegramGroupHistoryPromptContext({
576-
promptContext: baseVisiblePromptContext,
583+
promptContext: retainedVisiblePromptContext,
577584
entries: groupHistoryPromptEntries,
578585
});
579586

‎extensions/telegram/src/group-history-window.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,13 +128,10 @@ export function retainTelegramGroupHistoryPromptContext(params: {
128128
if (!isTelegramChatWindowPromptContext(entry)) {
129129
return [entry];
130130
}
131-
if (entryKeys.size === 0) {
132-
return [];
133-
}
134131
const payload = telegramChatWindowPayload(entry);
135132
const messages = telegramPromptMessages(payload).filter((message) => {
136133
const key = telegramPromptMessageKey(message);
137-
return Boolean(key && entryKeys.has(key));
134+
return message["is_reply_target"] === true || Boolean(key && entryKeys.has(key));
138135
});
139136
if (messages.length === 0) {
140137
return [];

‎src/channels/turn/execution.ts‎

Lines changed: 106 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -253,136 +253,141 @@ async function runPreparedChannelTurnCoreInTrace<
253253
}
254254
// Native commands can execute in an isolated command session while updating the
255255
// provider-routed target session. Keep that record target separate from dispatch.
256-
const recordSessionKey = resolveRecordSessionKey(params);
257-
if (params.ctxPayload.SessionTranscriptContext) {
258-
const { mergeSessionTranscriptContext } =
259-
await import("../inbound-event/session-transcript-context.runtime.js");
260-
await mergeSessionTranscriptContext({
261-
agentId: params.ctxPayload.AgentId,
262-
ctx: params.ctxPayload,
263-
sessionKey: recordSessionKey,
264-
storePath: params.storePath,
265-
});
266-
}
267-
emit({
268-
...params,
269-
event: {
270-
stage: "record",
271-
event: "start",
272-
messageId: params.messageId,
273-
sessionKey: recordSessionKey,
274-
admission: admission.kind,
275-
},
276-
});
256+
// The caller retains pending history across turns; finalize every admitted terminal
257+
// path before the next group turn can replay stale context.
277258
try {
278-
await params.recordInboundSession({
279-
storePath: params.storePath,
280-
sessionKey: recordSessionKey,
281-
ctx: params.ctxPayload,
282-
groupResolution: params.record?.groupResolution,
283-
createIfMissing: params.record?.createIfMissing,
284-
updateLastRoute: params.record?.updateLastRoute,
285-
onRecordError: params.record?.onRecordError ?? (() => undefined),
286-
trackSessionMetaTask: params.record?.trackSessionMetaTask,
287-
});
259+
const recordSessionKey = resolveRecordSessionKey(params);
260+
if (params.ctxPayload.SessionTranscriptContext) {
261+
const { mergeSessionTranscriptContext } =
262+
await import("../inbound-event/session-transcript-context.runtime.js");
263+
await mergeSessionTranscriptContext({
264+
agentId: params.ctxPayload.AgentId,
265+
ctx: params.ctxPayload,
266+
sessionKey: recordSessionKey,
267+
storePath: params.storePath,
268+
});
269+
}
288270
emit({
289271
...params,
290272
event: {
291273
stage: "record",
292-
event: "done",
274+
event: "start",
293275
messageId: params.messageId,
294276
sessionKey: recordSessionKey,
295277
admission: admission.kind,
296278
},
297279
});
298-
await params.afterRecord?.();
299-
await deliverPendingDeliveryNotice(recordSessionKey, params.storePath);
300-
} catch (err) {
280+
try {
281+
await params.recordInboundSession({
282+
storePath: params.storePath,
283+
sessionKey: recordSessionKey,
284+
ctx: params.ctxPayload,
285+
groupResolution: params.record?.groupResolution,
286+
createIfMissing: params.record?.createIfMissing,
287+
updateLastRoute: params.record?.updateLastRoute,
288+
onRecordError: params.record?.onRecordError ?? (() => undefined),
289+
trackSessionMetaTask: params.record?.trackSessionMetaTask,
290+
});
291+
emit({
292+
...params,
293+
event: {
294+
stage: "record",
295+
event: "done",
296+
messageId: params.messageId,
297+
sessionKey: recordSessionKey,
298+
admission: admission.kind,
299+
},
300+
});
301+
await params.afterRecord?.();
302+
await deliverPendingDeliveryNotice(recordSessionKey, params.storePath);
303+
} catch (err) {
304+
emit({
305+
...params,
306+
event: {
307+
stage: "record",
308+
event: "error",
309+
messageId: params.messageId,
310+
sessionKey: recordSessionKey,
311+
admission: admission.kind,
312+
error: err,
313+
},
314+
});
315+
try {
316+
await params.onPreDispatchFailure?.(err);
317+
} catch {
318+
// Preserve the original session-recording error.
319+
}
320+
throw err;
321+
}
322+
301323
emit({
302324
...params,
303325
event: {
304-
stage: "record",
305-
event: "error",
326+
stage: "dispatch",
327+
event: "start",
306328
messageId: params.messageId,
307-
sessionKey: recordSessionKey,
329+
sessionKey: params.ctxPayload.SessionKey ?? params.routeSessionKey,
308330
admission: admission.kind,
309-
error: err,
310331
},
311332
});
333+
let dispatchResult: TDispatchResult;
312334
try {
313-
await params.onPreDispatchFailure?.(err);
314-
} catch {
315-
// Preserve the original session-recording error.
335+
if (admission.kind === "observeOnly" && !options.suppressObserveOnlyDispatch) {
336+
await params.runDispatch();
337+
} else if (admission.kind === "observeOnly") {
338+
await params.runDispatchLifecycle?.onDispatchSkipped("observeOnly");
339+
}
340+
let processedOutcome: DispatchProcessedNote | undefined;
341+
if (admission.kind === "observeOnly") {
342+
dispatchResult = resolveObserveOnlyDispatchResult(params);
343+
} else {
344+
// The sink carries the dispatch's terminal outcome to the warning below
345+
// without widening the plugin-visible dispatch result contract.
346+
({ result: dispatchResult, processedOutcome } = await withDispatchProcessedOutcomeSink(() =>
347+
params.runDispatch(),
348+
));
349+
}
350+
maybeWarnZeroCountVisibleDispatch({
351+
...params,
352+
admission,
353+
dispatchResult,
354+
processedOutcome,
355+
});
356+
} catch (err) {
357+
emit({
358+
...params,
359+
event: {
360+
stage: "dispatch",
361+
event: "error",
362+
messageId: params.messageId,
363+
sessionKey: params.ctxPayload.SessionKey ?? params.routeSessionKey,
364+
admission: admission.kind,
365+
error: err,
366+
},
367+
});
368+
throw err;
316369
}
317-
throw err;
318-
}
319-
320-
emit({
321-
...params,
322-
event: {
323-
stage: "dispatch",
324-
event: "start",
325-
messageId: params.messageId,
326-
sessionKey: params.ctxPayload.SessionKey ?? params.routeSessionKey,
327-
admission: admission.kind,
328-
},
329-
});
330-
let dispatchResult: TDispatchResult;
331-
try {
332-
if (admission.kind === "observeOnly" && !options.suppressObserveOnlyDispatch) {
333-
await params.runDispatch();
334-
} else if (admission.kind === "observeOnly") {
335-
await params.runDispatchLifecycle?.onDispatchSkipped("observeOnly");
336-
}
337-
let processedOutcome: DispatchProcessedNote | undefined;
338-
if (admission.kind === "observeOnly") {
339-
dispatchResult = resolveObserveOnlyDispatchResult(params);
340-
} else {
341-
// The sink carries the dispatch's terminal outcome to the warning below
342-
// without widening the plugin-visible dispatch result contract.
343-
({ result: dispatchResult, processedOutcome } = await withDispatchProcessedOutcomeSink(() =>
344-
params.runDispatch(),
345-
));
346-
}
347-
maybeWarnZeroCountVisibleDispatch({
348-
...params,
349-
admission,
350-
dispatchResult,
351-
processedOutcome,
352-
});
353-
} catch (err) {
354370
emit({
355371
...params,
356372
event: {
357373
stage: "dispatch",
358-
event: "error",
374+
event: "done",
359375
messageId: params.messageId,
360376
sessionKey: params.ctxPayload.SessionKey ?? params.routeSessionKey,
361377
admission: admission.kind,
362-
error: err,
363378
},
364379
});
365-
throw err;
366-
}
367-
emit({
368-
...params,
369-
event: {
370-
stage: "dispatch",
371-
event: "done",
372-
messageId: params.messageId,
373-
sessionKey: params.ctxPayload.SessionKey ?? params.routeSessionKey,
374-
admission: admission.kind,
375-
},
376-
});
377-
clearPendingHistoryAfterTurn(params.history);
378380

379-
return {
380-
admission,
381-
dispatched: true,
382-
ctxPayload: params.ctxPayload,
383-
routeSessionKey: params.routeSessionKey,
384-
dispatchResult,
385-
};
381+
return {
382+
admission,
383+
dispatched: true,
384+
ctxPayload: params.ctxPayload,
385+
routeSessionKey: params.routeSessionKey,
386+
dispatchResult,
387+
};
388+
} finally {
389+
clearPendingHistoryAfterTurn(params.history);
390+
}
386391
}
387392

388393
export async function runPreparedChannelTurn<

0 commit comments

Comments
 (0)