From 31e707c238a731421beec87445dbce41c3a680d3 Mon Sep 17 00:00:00 2001 From: 0xmrpeter <0xmrpeter@gmail.com> Date: Mon, 23 Mar 2026 16:01:17 +0700 Subject: [PATCH] fix(telegram): improve command handling and session management - Added text processing to strip leading slashes from unrecognized commands in the Telegram adapter to prevent agent subprocesses from hanging. - Updated session cancellation messages for clarity, changing "Cancel session command" to "Abort prompt command" and adjusting user feedback for session status. - Modified session resumption logic to allow resuming cancelled sessions while preventing errors from being resumed. - Implemented abort functionality in the prompt queue to handle ongoing processes more gracefully. --- src/adapters/telegram/adapter.ts | 13 ++++++++++--- src/adapters/telegram/commands/session.ts | 14 +++++++------- src/core/core.ts | 6 +++--- src/core/prompt-queue.ts | 20 ++++++++++++++++++-- 4 files changed, 38 insertions(+), 15 deletions(-) diff --git a/src/adapters/telegram/adapter.ts b/src/adapters/telegram/adapter.ts index b01ba70..6cbcb6d 100644 --- a/src/adapters/telegram/adapter.ts +++ b/src/adapters/telegram/adapter.ts @@ -367,6 +367,7 @@ export class TelegramAdapter extends ChannelAdapter { private setupRoutes(): void { this.bot.on("message:text", async (ctx) => { const threadId = ctx.message.message_thread_id; + const text = ctx.message.text; // Check for pending workspace input from interactive /new flow if (await handlePendingWorkspaceInput(ctx, this.core, this.telegramConfig.chatId, this.assistantTopicId)) { @@ -386,6 +387,11 @@ export class TelegramAdapter extends ChannelAdapter { // Notification topic → ignore if (threadId === this.notificationTopicId) return; + // Strip leading "/" from unrecognized commands — registered commands + // (e.g. /new, /cancel) are already handled by bot.command() above. + // Unrecognized slash commands can cause agent subprocesses to hang. + const forwardText = text.startsWith("/") ? text.slice(1) : text; + // Assistant topic → forward to assistant session if (threadId === this.assistantTopicId) { if (!this.assistantSession) { @@ -394,7 +400,7 @@ export class TelegramAdapter extends ChannelAdapter { } await this.draftManager.finalize(this.assistantSession.id, this.assistantSession.id); ctx.replyWithChatAction("typing").catch(() => {}); - handleAssistantMessage(this.assistantSession, ctx.message.text).catch( + handleAssistantMessage(this.assistantSession, forwardText).catch( (err) => log.error({ err }, "Assistant error"), ); return; @@ -413,7 +419,7 @@ export class TelegramAdapter extends ChannelAdapter { channelId: "telegram", threadId: String(threadId), userId: String(ctx.from.id), - text: ctx.message.text, + text: forwardText, }) .catch((err) => log.error({ err }, "handleMessage error")); }); @@ -854,7 +860,8 @@ export class TelegramAdapter extends ChannelAdapter { const sessionId = this.resolveSessionId(threadId) || "unknown"; const att = await this.fileService.saveFile(sessionId, fileName, buffer, mimeType); - const text = caption || `[${att.type === "image" ? "Photo" : att.type === "audio" ? "Audio" : "File"}: ${att.fileName}]`; + const rawText = caption || `[${att.type === "image" ? "Photo" : att.type === "audio" ? "Audio" : "File"}: ${att.fileName}]`; + const text = rawText.startsWith("/") ? rawText.slice(1) : rawText; // Assistant topic if (threadId === this.assistantTopicId) { diff --git a/src/adapters/telegram/commands/session.ts b/src/adapters/telegram/commands/session.ts index ac9bc61..9b14580 100644 --- a/src/adapters/telegram/commands/session.ts +++ b/src/adapters/telegram/commands/session.ts @@ -31,18 +31,18 @@ export async function handleCancel( String(threadId), ); if (session) { - log.info({ sessionId: session.id }, "Cancel session command"); + log.info({ sessionId: session.id }, "Abort prompt command"); await session.abortPrompt(); - await ctx.reply("⛔ Session cancelled.", { parse_mode: "HTML" }); + await ctx.reply("⛔ Prompt aborted. Session is still active — send a new message to continue.", { parse_mode: "HTML" }); return; } - // Fallback: cancel from store when session not in memory (e.g. after restart) + // Fallback: session not in memory — nothing to abort, but session can + // still be resumed when the user sends a new message. const record = core.sessionManager.getRecordByThread("telegram", String(threadId)); - if (record && record.status !== "cancelled" && record.status !== "error") { - log.info({ sessionId: record.sessionId }, "Cancel session command (from store)"); - await core.sessionManager.cancelSession(record.sessionId); - await ctx.reply("⛔ Session cancelled.", { parse_mode: "HTML" }); + if (record && record.status !== "error") { + log.info({ sessionId: record.sessionId, status: record.status }, "Cancel command — no active prompt to abort"); + await ctx.reply("ℹ️ No active prompt to cancel. Send a new message to resume the session.", { parse_mode: "HTML" }); } } diff --git a/src/core/core.ts b/src/core/core.ts index a7460d2..e75fb27 100644 --- a/src/core/core.ts +++ b/src/core/core.ts @@ -424,11 +424,11 @@ export class OpenACPCore { return null; } - // Don't resume cancelled/error sessions - if (record.status === "cancelled" || record.status === "error") { + // Don't resume errored sessions (cancelled sessions can still be resumed) + if (record.status === "error") { log.debug( { threadId: message.threadId, sessionId: record.sessionId, status: record.status }, - "Skipping resume of cancelled/error session", + "Skipping resume of error session", ); return null; } diff --git a/src/core/prompt-queue.ts b/src/core/prompt-queue.ts index 5f83ede..d1499e2 100644 --- a/src/core/prompt-queue.ts +++ b/src/core/prompt-queue.ts @@ -6,6 +6,7 @@ import type { Attachment } from './types.js' export class PromptQueue { private queue: Array<{ text: string; attachments?: Attachment[]; resolve: () => void }> = [] private processing = false + private abortController: AbortController | null = null constructor( private processor: (text: string, attachments?: Attachment[]) => Promise, @@ -23,11 +24,22 @@ export class PromptQueue { private async process(text: string, attachments?: Attachment[]): Promise { this.processing = true + this.abortController = new AbortController() + const { signal } = this.abortController try { - await this.processor(text, attachments) + await Promise.race([ + this.processor(text, attachments), + new Promise((_, reject) => { + signal.addEventListener('abort', () => reject(new Error('Prompt aborted')), { once: true }) + }), + ]) } catch (err) { - this.onError?.(err) + // Only forward non-abort errors to onError handler + if (!(err instanceof Error && err.message === 'Prompt aborted')) { + this.onError?.(err) + } } finally { + this.abortController = null this.processing = false this.drainNext() } @@ -41,6 +53,10 @@ export class PromptQueue { } clear(): void { + // Abort the currently running prompt so the queue can drain + if (this.abortController) { + this.abortController.abort() + } // Resolve pending promises so callers don't hang for (const item of this.queue) { item.resolve()