Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(telegram): show editable status message during tool execution

Jiayuan Zhangdde8cc542aca
diff --git a/apps/gateway/telegram/telegram.service.ts b/apps/gateway/telegram/telegram.service.ts
index 9f76df6a1b..32f79eb99f 100644
--- a/apps/gateway/telegram/telegram.service.ts
+++ b/apps/gateway/telegram/telegram.service.ts
@@ -144,6 +144,8 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {
private typingTimers = new Map<string, ReturnType<typeof setInterval>>();
/** Tracks the originating message for reply_to & reaction cleanup, keyed by deviceId */
private messageContexts = new Map<string, MessageContext>();
+ /** Editable status message IDs for tool narration, keyed by deviceId */
+ private statusMessages = new Map<string, { chatId: number; messageId: number }>();
private readonly logger = new Logger(TelegramService.name);
@@ -635,6 +637,58 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {
}
}
+ /**
+ * Edit an existing message with HTML formatting, fallback to plain text.
+ */
+ private async editFormatted(
+ chatId: number,
+ messageId: number,
+ text: string,
+ ): Promise<void> {
+ if (!this.bot) return;
+
+ const html = markdownToTelegramHtml(text);
+ try {
+ await this.bot.api.editMessageText(chatId, messageId, html, { parse_mode: "HTML" });
+ } catch (err) {
+ if (isParseError(err)) {
+ this.logger.warn("HTML parse failed on edit, retrying as plain text");
+ await this.bot.api.editMessageText(chatId, messageId, text);
+ } else {
+ throw err;
+ }
+ }
+ }
+
+ /**
+ * Send or edit a status message for tool narration.
+ * First call sends a new reply; subsequent calls edit the same message.
+ */
+ private async sendOrEditStatus(deviceId: string, text: string): Promise<void> {
+ if (!this.bot) return;
+
+ const user = await this.userStore.findByDeviceId(deviceId);
+ if (!user) return;
+
+ const context = this.messageContexts.get(deviceId);
+ const chatId = context?.telegramChatId ?? Number(user.telegramUserId);
+ const existing = this.statusMessages.get(deviceId);
+
+ try {
+ if (existing) {
+ await this.editFormatted(existing.chatId, existing.messageId, text);
+ } else {
+ const html = markdownToTelegramHtml(text);
+ const extra: Record<string, unknown> = { parse_mode: "HTML" };
+ if (context) extra["reply_to_message_id"] = context.telegramMessageId;
+ const msg = await this.bot.api.sendMessage(chatId, html, extra);
+ this.statusMessages.set(deviceId, { chatId, messageId: msg.message_id });
+ }
+ } catch (err) {
+ this.logger.warn(`Failed to send/edit status: ${err}`);
+ }
+ }
+
/** Send a file (photo/document/video/audio) to a Telegram user */
private async sendFileToTelegram(
deviceId: string,
@@ -780,6 +834,7 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {
await this.removeReaction(context.telegramChatId, context.telegramMessageId);
this.messageContexts.delete(deviceId);
}
+ this.statusMessages.delete(deviceId);
}
// ── Connection & routing ──
@@ -1005,11 +1060,18 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {
if (event.type === "message_end") {
const agentMsg = (event as { message?: { content?: Array<{ type: string; text?: string }> } }).message;
- // Skip tool narration: if the message contains tool_use blocks,
+ // Tool narration: if the message contains tool_use blocks,
// it's intermediate text (e.g. "Let me search...") before a tool call.
- // Keep typing and wait for the final answer.
+ // Send/edit an editable status message and keep typing.
const hasToolUse = agentMsg?.content?.some((c) => c.type === "tool_use") ?? false;
if (hasToolUse) {
+ const narration = agentMsg?.content
+ ?.filter((c) => c.type === "text" && c.text)
+ .map((c) => c.text!)
+ .join("") ?? "";
+ if (narration) {
+ void this.sendOrEditStatus(deviceId, narration);
+ }
return;
}
diff --git a/packages/core/src/channels/manager.ts b/packages/core/src/channels/manager.ts
index 7e6009ffac..cbe7800dff 100644
--- a/packages/core/src/channels/manager.ts
+++ b/packages/core/src/channels/manager.ts
@@ -23,7 +23,7 @@ import { listChannels } from "./registry.js";
import { loadChannelsConfig } from "./config.js";
import { MessageAggregator, DEFAULT_CHUNKER_CONFIG } from "../hub/message-aggregator.js";
import { isHeartbeatAckEvent } from "../hub/heartbeat-filter.js";
-import { hasToolUse } from "../agent/extract-text.js";
+import { extractText, hasToolUse } from "../agent/extract-text.js";
import type { AsyncAgent } from "../agent/async-agent.js";
import type { ChannelInfo } from "../agent/system-prompt/types.js";
import { transcribeAudio } from "../media/transcribe.js";
@@ -72,6 +72,8 @@ export class ChannelManager {
private aggregator: MessageAggregator | null = null;
/** Typing indicator interval (repeats every 5s to keep Telegram typing visible) */
private typingTimer: ReturnType<typeof setInterval> | null = null;
+ /** Platform message ID of the editable status message (for tool narration updates) */
+ private statusMessageId: string | null = null;
/**
* Inbound message debouncer — batches rapid-fire messages from the same
* conversation into a single agent.write() call.
@@ -227,6 +229,7 @@ export class ChannelManager {
}
this.activeRoute = null;
this.activeAcks = [];
+ this.statusMessageId = null;
if (this.pendingRoutes.length === 0) {
console.log("[Channels] agent_end: no more pending, stopping typing");
this.stopTyping();
@@ -248,6 +251,7 @@ export class ChannelManager {
}
this.activeRoute = null;
this.activeAcks = [];
+ this.statusMessageId = null;
const errorMsg = (event as { message?: string }).message ?? "Unknown error";
console.error(`[Channels] Agent error: ${errorMsg}`);
const route = this.lastRoute;
@@ -280,15 +284,21 @@ export class ChannelManager {
this.createAggregator();
}
- // Skip tool narration: if the assistant message contains tool_use blocks,
- // it's intermediate narration (e.g. "Let me search...") before a tool call,
- // not the final answer. Discard the buffered text instead of sending it.
+ // Tool narration: if the assistant message contains tool_use blocks,
+ // it's intermediate narration (e.g. "Let me search...") before a tool call.
+ // Send/edit an editable status message instead of the normal reply flow.
if (event.type === "message_end" && role === "assistant") {
const message = (event as { message?: Parameters<typeof hasToolUse>[0] }).message;
if (hasToolUse(message)) {
- console.log("[Channels] Skipping tool narration message (has tool_use blocks)");
this.aggregator?.reset();
this.aggregator = null;
+
+ const route = this.activeRoute ?? this.lastRoute;
+ const narration = extractText(message);
+ if (route && narration) {
+ const { plugin, deliveryCtx } = route;
+ void this.sendOrEditStatus(plugin, deliveryCtx, narration);
+ }
return;
}
}
@@ -335,6 +345,31 @@ export class ChannelManager {
);
}
+ /**
+ * Send or edit a status message for tool narration.
+ * First call sends a new editable reply; subsequent calls edit the same message.
+ * Falls back to no-op if the plugin doesn't support editable messages.
+ */
+ private async sendOrEditStatus(
+ plugin: ChannelPlugin,
+ deliveryCtx: DeliveryContext,
+ text: string,
+ ): Promise<void> {
+ try {
+ if (this.statusMessageId && plugin.outbound.editText) {
+ console.log(`[Channels] Editing status message ${this.statusMessageId}`);
+ await plugin.outbound.editText(deliveryCtx, this.statusMessageId, text);
+ } else if (plugin.outbound.replyTextEditable) {
+ const msgId = await plugin.outbound.replyTextEditable(deliveryCtx, text);
+ this.statusMessageId = msgId;
+ console.log(`[Channels] Sent editable status message ${msgId}`);
+ }
+ // If plugin doesn't support editable messages, silently skip (typing indicator still active)
+ } catch (err) {
+ console.error(`[Channels] Failed to send/edit status: ${err}`);
+ }
+ }
+
/**
* Incoming channel message → update lastRoute → forward to Hub's agent.
*/
@@ -587,6 +622,7 @@ export class ChannelManager {
this.ackBuffer = [];
this.pendingRoutes = [];
this.aggregator = null;
+ this.statusMessageId = null;
}
handle.abortController.abort();
@@ -624,6 +660,7 @@ export class ChannelManager {
this.ackBuffer = [];
this.pendingRoutes = [];
this.aggregator = null;
+ this.statusMessageId = null;
}
/** Clear the last route (e.g. when desktop user sends a message) */
diff --git a/packages/core/src/channels/plugins/telegram.ts b/packages/core/src/channels/plugins/telegram.ts
index f7f31ce605..dca4116c3c 100644
--- a/packages/core/src/channels/plugins/telegram.ts
+++ b/packages/core/src/channels/plugins/telegram.ts
@@ -30,20 +30,42 @@ function isParseError(err: unknown): boolean {
return err instanceof GrammyError && err.description.includes("can't parse entities");
}
-/** Send a message with HTML formatting, fallback to plain text on parse error */
+/** Send a message with HTML formatting, fallback to plain text on parse error. Returns message ID. */
async function sendFormatted(
bot: Bot,
chatId: number,
text: string,
extra?: Record<string, unknown>,
-): Promise<void> {
+): Promise<number> {
const html = markdownToTelegramHtml(text);
try {
- await bot.api.sendMessage(chatId, html, { ...extra, parse_mode: "HTML" });
+ const msg = await bot.api.sendMessage(chatId, html, { ...extra, parse_mode: "HTML" });
+ return msg.message_id;
} catch (err) {
if (isParseError(err)) {
console.warn("[Telegram] HTML parse failed, retrying as plain text");
- await bot.api.sendMessage(chatId, text, extra);
+ const msg = await bot.api.sendMessage(chatId, text, extra);
+ return msg.message_id;
+ } else {
+ throw err;
+ }
+ }
+}
+
+/** Edit an existing message with HTML formatting, fallback to plain text on parse error */
+async function editFormatted(
+ bot: Bot,
+ chatId: number,
+ messageId: number,
+ text: string,
+): Promise<void> {
+ const html = markdownToTelegramHtml(text);
+ try {
+ await bot.api.editMessageText(chatId, messageId, html, { parse_mode: "HTML" });
+ } catch (err) {
+ if (isParseError(err)) {
+ console.warn("[Telegram] HTML parse failed on edit, retrying as plain text");
+ await bot.api.editMessageText(chatId, messageId, text);
} else {
throw err;
}
@@ -322,6 +344,29 @@ export const telegramChannel: ChannelPlugin = {
}
},
+ async replyTextEditable(ctx: DeliveryContext, text: string): Promise<string> {
+ const bot = bots.get(ctx.accountId);
+ if (!bot) throw new Error(`No Telegram bot for account ${ctx.accountId}`);
+
+ const chatId = Number(ctx.conversationId);
+ const extra: Record<string, unknown> = {};
+ if (ctx.replyToMessageId) {
+ extra["reply_to_message_id"] = Number(ctx.replyToMessageId);
+ }
+
+ console.log(`[Telegram] Sending editable status to chatId=${chatId}`);
+ const msgId = await sendFormatted(bot, chatId, text, extra);
+ return String(msgId);
+ },
+
+ async editText(ctx: DeliveryContext, messageId: string, text: string): Promise<void> {
+ const bot = bots.get(ctx.accountId);
+ if (!bot) throw new Error(`No Telegram bot for account ${ctx.accountId}`);
+
+ console.log(`[Telegram] Editing message ${messageId} in chatId=${ctx.conversationId}`);
+ await editFormatted(bot, Number(ctx.conversationId), Number(messageId), text);
+ },
+
async sendMedia(ctx: DeliveryContext, media: OutboundMedia): Promise<void> {
const bot = bots.get(ctx.accountId);
if (!bot) throw new Error(`No Telegram bot for account ${ctx.accountId}`);
diff --git a/packages/core/src/channels/types.ts b/packages/core/src/channels/types.ts
index fd9fe2c12d..e2d69bdb20 100644
--- a/packages/core/src/channels/types.ts
+++ b/packages/core/src/channels/types.ts
@@ -127,6 +127,15 @@ export interface ChannelOutboundAdapter {
* Called when processing completes to clear the ACK indicator.
*/
removeReaction?(ctx: DeliveryContext): Promise<void>;
+ /**
+ * Reply with an editable status message, returning its platform message ID.
+ * Used for tool narration: the message is updated in-place as the agent works.
+ */
+ replyTextEditable?(ctx: DeliveryContext, text: string): Promise<string>;
+ /**
+ * Edit a previously sent message by its platform message ID.
+ */
+ editText?(ctx: DeliveryContext, messageId: string, text: string): Promise<void>;
}
// ─── Channel Plugin ───