1- // Telegram plugin module coordinates one inbound message dispatch lifecycle.
21import { getGlobalHookRunner } from "openclaw/plugin-sdk/plugin-runtime" ;
32import { createSubsystemLogger , danger , logVerbose } from "openclaw/plugin-sdk/runtime-env" ;
43import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime" ;
54import { resolveDispatchTelegramContext } from "./bot-message-dispatch-context.js" ;
6- import { createTelegramDeliveryController } from "./bot-message-dispatch-delivery.js" ;
7- import { createTelegramDraftController } from "./bot-message-dispatch-draft.js" ;
8- import { createTelegramProgressController } from "./bot-message-dispatch-progress.js" ;
9- import { createTelegramReplyDelivery } from "./bot-message-dispatch-reply.js" ;
5+ import {
6+ createDeliveryState ,
7+ deliverFallback ,
8+ deliverProgressCollapseSummary ,
9+ finalizePendingAnswerBlockDraft ,
10+ } from "./bot-message-dispatch-delivery.js" ;
11+ import {
12+ cleanupDrafts ,
13+ createDraftState ,
14+ prepareAnswerLaneForToolProgress ,
15+ waitForDraftEvents ,
16+ } from "./bot-message-dispatch-draft.js" ;
17+ import { createProgressState } from "./bot-message-dispatch-progress.js" ;
18+ import { createReplyState } from "./bot-message-dispatch-reply.js" ;
1019import {
1120 createFreshTelegramSessionEntryLoader ,
1221 resolveTelegramReasoningLevel ,
@@ -29,8 +38,8 @@ import {
2938} from "./bot-message-dispatch.runtime.js" ;
3039import type {
3140 DispatchTelegramMessageParams ,
41+ TelegramDispatchTurn ,
3242 TelegramDispatchResult ,
33- TelegramDispatchTurnState ,
3443} from "./bot-message-dispatch.types.js" ;
3544import { getTelegramTextParts , resolveTelegramReplyId } from "./bot/helpers.js" ;
3645import {
@@ -73,8 +82,6 @@ function includeStickerDescription(params: {
7382 if ( ! current ) {
7483 return params . formattedDescription ;
7584 }
76- // Cached descriptions can already be present from inbound context construction.
77- // Keep that body intact so captions, forwarded text, and supplemental context survive.
7885 if ( params . body . includes ( params . formattedDescription ) ) {
7986 return params . body ;
8087 }
@@ -142,7 +149,6 @@ function resolveTelegramQuoteContext(params: {
142149 : undefined ;
143150 return {
144151 draftReplyToMessageId,
145- hasTelegramQuoteReply : replyToMode !== "off" && replyQuoteText != null ,
146152 replyQuoteByMessageId,
147153 replyQuoteEntities : Array . isArray ( context . ctxPayload . ReplyToQuoteEntities )
148154 ? context . ctxPayload . ReplyToQuoteEntities
@@ -274,21 +280,22 @@ function scheduleDmTopicLabel(params: {
274280 } ) ( ) ;
275281}
276282
277- export const dispatchTelegramMessage = async ( {
278- context,
279- bot,
280- cfg,
281- runtime,
282- replyToMode,
283- streamMode,
284- textLimit,
285- telegramCfg,
286- telegramDeps : injectedTelegramDeps ,
287- opts,
288- retryDispatchErrors = false ,
289- suppressFailureFallback = false ,
290- turnAdoptionLifecycle,
291- } : DispatchTelegramMessageParams ) : Promise < TelegramDispatchResult > => {
283+ export const dispatchTelegramMessage = async (
284+ dispatchParams : DispatchTelegramMessageParams ,
285+ ) : Promise < TelegramDispatchResult > => {
286+ const {
287+ context,
288+ bot,
289+ cfg,
290+ runtime,
291+ replyToMode,
292+ streamMode,
293+ telegramCfg,
294+ telegramDeps : injectedTelegramDeps ,
295+ retryDispatchErrors = false ,
296+ suppressFailureFallback = false ,
297+ turnAdoptionLifecycle,
298+ } = dispatchParams ;
292299 const dispatchStartedAt = Date . now ( ) ;
293300 const dispatchContext = resolveDispatchTelegramContext ( { context } ) ;
294301 const telegramDeps =
@@ -308,8 +315,6 @@ export const dispatchTelegramMessage = async ({
308315 agentId : dispatchContext . route . agentId ,
309316 loadFreshSessionEntry,
310317 } ) ;
311- const forceBlockStreamingForReasoning =
312- resolvedReasoningLevel === "on" && streamMode !== "progress" ;
313318 const quote = resolveTelegramQuoteContext ( { context : dispatchContext , replyToMode } ) ;
314319 // Draft messages are provider-visible before final modifiers run. Suppress them when a hook
315320 // can rewrite or cancel, or the original payload can flash before the normal delivery gate.
@@ -318,87 +323,46 @@ export const dispatchTelegramMessage = async ({
318323 ( hookRunner ?. hasHooks ( "reply_payload_sending" ) ?? false ) ||
319324 ( hookRunner ?. hasHooks ( "message_sending" ) ?? false )
320325 ) ;
321- // Pre-adoption abort is drain-owned via turnAdoptionLifecycle.abortSignal.
322326 const isDispatchSuperseded = ( ) => turnAdoptionLifecycle ?. abortSignal ?. aborted === true ;
323- const dispatchGeneration = 0 ;
324- const draft = createTelegramDraftController ( {
325- accountId : dispatchContext . route . accountId ,
327+ const turnConfig = {
328+ ...dispatchParams ,
326329 allowProviderPreview,
327- bot,
328- cfg,
329- chatId : dispatchContext . chatId ,
330- draftReplyToMessageId : quote . draftReplyToMessageId ,
331- forceBlockStreamingForReasoning,
332- hasTelegramQuoteReply : quote . hasTelegramQuoteReply ,
333- isDispatchSuperseded,
334- isRoomEvent,
335- replyToMode,
336- resolvedReasoningLevel,
337- streamMode,
338- tableMode,
339- telegramCfg,
340- telegramDeps,
341- textLimit,
342- threadSpec : dispatchContext . threadSpec ,
343- } ) ;
344- const progress = createTelegramProgressController ( {
345- accountId : dispatchContext . route . accountId ,
346- chatId : dispatchContext . chatId ,
347- draft,
348- statusReactionController : status . controller ,
349- streamMode,
350- streamReasoningInProgressDraft : draft . streamReasoningInProgressDraft ,
351- telegramCfg,
352- threadId : dispatchContext . threadSpec . id ,
353- } ) ;
354- const delivery = createTelegramDeliveryController ( {
355- bot,
356- cfg,
357330 chunkMode : resolveChunkMode ( cfg , "telegram" , dispatchContext . route . accountId ) ,
358331 context : dispatchContext ,
359332 dispatchStartedAt,
360- draft,
361333 draftReplyToMessageId : quote . draftReplyToMessageId ,
362- isDispatchSuperseded,
334+ isSuperseded : isDispatchSuperseded ,
363335 loadFreshSessionEntry,
364336 mediaLocalRoots : getAgentScopedMediaLocalRoots ( cfg , dispatchContext . route . agentId ) ,
365- opts,
366- progress,
367337 replyQuoteByMessageId : quote . replyQuoteByMessageId ,
368338 replyQuoteEntities : quote . replyQuoteEntities ,
369339 replyQuoteMessageId : quote . replyQuoteMessageId ,
370340 replyQuotePosition : quote . replyQuotePosition ,
371341 replyQuoteText : quote . replyQuoteText ,
372- replyToMode,
373- runtime,
374- streamMode,
342+ resolvedReasoningLevel,
343+ statusReactionController : status . controller ,
375344 tableMode,
376- telegramCfg,
377345 telegramDeps,
378- textLimit,
379- threadSpec : dispatchContext . threadSpec ,
380- } ) ;
381- const state : TelegramDispatchTurnState = {
346+ } ;
347+ const draftState = createDraftState ( turnConfig ) ;
348+ const progressState = createProgressState (
349+ turnConfig ,
350+ draftState ,
351+ ( ) => turn ,
352+ async ( ) => await prepareAnswerLaneForToolProgress ( turn ) ,
353+ ) ;
354+ const deliveryState = createDeliveryState ( { ...turnConfig , lanes : draftState . lanes } , ( ) => turn ) ;
355+ const turn : TelegramDispatchTurn = {
356+ ...turnConfig ,
357+ ...draftState ,
358+ ...progressState ,
359+ ...deliveryState ,
360+ ...createReplyState ( ) ,
382361 queuedFinal : false ,
383362 noVisibleReplyFallbackEligible : false ,
384363 suppressSilentReplyFallback : false ,
385364 hadErrorReplyFailureOrSkip : false ,
386365 } ;
387- const reply = createTelegramReplyDelivery ( {
388- cfg,
389- context : dispatchContext ,
390- delivery,
391- draft,
392- fence : {
393- generation : ( ) => dispatchGeneration ,
394- isSuperseded : isDispatchSuperseded ,
395- } ,
396- progress,
397- runtime,
398- state,
399- streamMode,
400- telegramCfg,
401- } ) ;
402366
403367 let isFirstTurnInSession = false ;
404368 let dispatchWasSuperseded : boolean ;
@@ -427,42 +391,30 @@ export const dispatchTelegramMessage = async ({
427391 void status . controller . setThinking ( ) ;
428392 }
429393 try {
430- turnDispatched = await runTelegramDispatchTurn ( {
431- cfg,
432- context : dispatchContext ,
433- delivery,
434- draft,
435- turnAdoptionLifecycle,
436- isSuperseded : isDispatchSuperseded ,
437- progress,
438- reply,
439- state,
440- statusReactionController : status . controller ,
441- streamMode,
442- telegramCfg,
443- telegramDeps,
444- } ) ;
394+ turnDispatched = await runTelegramDispatchTurn ( turn ) ;
445395 } catch ( err ) {
446- state . dispatchError = err ;
396+ turn . dispatchError = err ;
447397 runtime . error ?.( danger ( `telegram dispatch failed: ${ String ( err ) } ` ) ) ;
448398 } finally {
449- progress . cancel ( ) ;
450- await draft . waitForEvents ( ) ;
399+ // Terminal order: stop producers, drain queued drafts, materialize accepted text,
400+ // clean previews, then collapse the progress window.
401+ turn . progressCompositor . cancel ( ) ;
402+ await waitForDraftEvents ( turn ) ;
451403 try {
452- await delivery . finalizePendingAnswerBlockDraft ( state ) ;
404+ await finalizePendingAnswerBlockDraft ( turn ) ;
453405 } catch ( err ) {
454- state . dispatchError ??= err ;
406+ turn . dispatchError ??= err ;
455407 runtime . error ?.( danger ( `telegram terminal block delivery failed: ${ String ( err ) } ` ) ) ;
456408 }
457- await draft . cleanup ( isDispatchSuperseded ( ) ) ;
409+ await cleanupDrafts ( turn , isDispatchSuperseded ( ) ) ;
458410 if (
459411 streamMode === "progress" &&
460- progress . sawProgressFinal ( ) &&
461- ! state . dispatchError &&
462- ! state . hadErrorReplyFailureOrSkip &&
412+ turn . sawProgressFinal &&
413+ ! turn . dispatchError &&
414+ ! turn . hadErrorReplyFailureOrSkip &&
463415 ! isDispatchSuperseded ( )
464416 ) {
465- await delivery . deliverProgressCollapseSummary ( ) ;
417+ await deliverProgressCollapseSummary ( turn ) ;
466418 }
467419 }
468420 } finally {
@@ -479,60 +431,61 @@ export const dispatchTelegramMessage = async ({
479431 return { kind : "completed" } ;
480432 }
481433
482- const deliverySummary = delivery . snapshot ( ) ;
434+ const deliverySummary = turn . deliveryState . snapshot ( ) ;
483435 let sentFallback = false ;
484436 const shouldSendFailureFallback =
485437 ! isRoomEvent &&
486438 ! suppressFailureFallback &&
487- ! progress . finalAnswerDelivered ( ) &&
488- ( state . dispatchError ||
439+ ! turn . finalAnswerDelivered &&
440+ ( turn . dispatchError ||
489441 deliverySummary . failedNonSilent > 0 ||
490- ( deliverySummary . skippedNonSilent > 0 && ! state . suppressSilentReplyFallback ) ) ;
442+ ( deliverySummary . skippedNonSilent > 0 && ! turn . suppressSilentReplyFallback ) ) ;
491443 if ( shouldSendFailureFallback ) {
492- const fallbackText = state . dispatchError
444+ const fallbackText = turn . dispatchError
493445 ? "Something went wrong while processing your request. Please try again."
494446 : EMPTY_RESPONSE_FALLBACK ;
495- const result = await delivery . deliverFallback (
447+ const result = await deliverFallback (
448+ turn ,
496449 [ { text : fallbackText } ] ,
497450 telegramCfg . silentErrorReplies === true &&
498- ( state . dispatchError != null || state . hadErrorReplyFailureOrSkip ) ,
451+ ( turn . dispatchError != null || turn . hadErrorReplyFailureOrSkip ) ,
499452 ) ;
500453 sentFallback = result . delivered ;
501454 }
502455
503456 if (
504457 ! sentFallback &&
505- ! state . dispatchError &&
458+ ! turn . dispatchError &&
506459 ! deliverySummary . delivered &&
507- ! state . suppressSilentReplyFallback &&
508- ! state . queuedFinal &&
509- state . noVisibleReplyFallbackEligible
460+ ! turn . suppressSilentReplyFallback &&
461+ ! turn . queuedFinal &&
462+ turn . noVisibleReplyFallbackEligible
510463 ) {
511- sentFallback = ( await delivery . deliverFallback ( [ { text : EMPTY_RESPONSE_FALLBACK } ] , false ) )
464+ sentFallback = ( await deliverFallback ( turn , [ { text : EMPTY_RESPONSE_FALLBACK } ] , false ) )
512465 . delivered ;
513466 silentReplyDispatchLogger . debug ( "telegram recovered eligible turn without visible response" , {
514467 hasSessionKey : Boolean ( dispatchContext . ctxPayload . SessionKey ) ,
515468 hasChatId : dispatchContext . chatId != null ,
516- queuedFinal : state . queuedFinal ,
469+ queuedFinal : turn . queuedFinal ,
517470 sentFallback,
518471 } ) ;
519472 }
520473
521474 const hasFinalResponse =
522- progress . finalAnswerDelivered ( ) ||
475+ turn . finalAnswerDelivered ||
523476 sentFallback ||
524- state . suppressSilentReplyFallback ||
525- state . queuedFinal ;
477+ turn . suppressSilentReplyFallback ||
478+ turn . queuedFinal ;
526479 const hasVisibleResponse =
527480 deliverySummary . delivered ||
528481 sentFallback ||
529- state . suppressSilentReplyFallback ||
530- state . queuedFinal ;
482+ turn . suppressSilentReplyFallback ||
483+ turn . queuedFinal ;
531484 const deliveryFailureWithoutFinalResponse =
532- ! progress . finalAnswerDelivered ( ) &&
485+ ! turn . finalAnswerDelivered &&
533486 ( deliverySummary . skippedNonSilent > 0 || deliverySummary . failedNonSilent > 0 ) ;
534487 const retryableDispatchFailure =
535- state . dispatchError ??
488+ turn . dispatchError ??
536489 ( deliveryFailureWithoutFinalResponse
537490 ? new Error (
538491 `Telegram reply delivery failed without a final response (failed=${ deliverySummary . failedNonSilent } , skipped=${ deliverySummary . skippedNonSilent } )` ,
@@ -544,8 +497,8 @@ export const dispatchTelegramMessage = async ({
544497 }
545498 const shouldReturnRetryableDispatchFailure =
546499 retryDispatchErrors &&
547- ( ( state . dispatchError != null && ! hasFinalResponse ) ||
548- ( state . dispatchError == null && deliveryFailureWithoutFinalResponse && ! hasVisibleResponse ) ) ;
500+ ( ( turn . dispatchError != null && ! hasFinalResponse ) ||
501+ ( turn . dispatchError == null && deliveryFailureWithoutFinalResponse && ! hasVisibleResponse ) ) ;
549502 if ( retryableDispatchFailure && shouldReturnRetryableDispatchFailure ) {
550503 return { kind : "failed-retryable" , error : retryableDispatchFailure } ;
551504 }
@@ -564,7 +517,7 @@ export const dispatchTelegramMessage = async ({
564517 status . finalizeInBackground (
565518 {
566519 outcome :
567- ! progress . finalAnswerDelivered ( ) && ( state . dispatchError != null || sentFallback )
520+ ! turn . finalAnswerDelivered && ( turn . dispatchError != null || sentFallback )
568521 ? "error"
569522 : "done" ,
570523 } ,
0 commit comments