Merge pull request #2 from lngdao/main

Fix permission button deadlock and improve tool call display
This commit is contained in:
Mr.Peter 2026-03-19 17:55:17 +07:00 committed by GitHub
commit af2cb6098e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 106 additions and 54 deletions

View File

@ -12,7 +12,7 @@ export class TelegramAdapter extends ChannelAdapter {
private bot!: Bot
private telegramConfig: TelegramChannelConfig
private sessionDrafts: Map<string, MessageDraft> = new Map()
private toolCallMessages: Map<string, Map<string, number>> = new Map() // sessionId → (toolCallId → msgId)
private toolCallMessages: Map<string, Map<string, { msgId: number; name: string; kind?: string }>> = new Map() // sessionId → (toolCallId → state)
private permissionHandler!: PermissionHandler
private assistantSession: Session | null = null
private notificationTopicId!: number
@ -26,9 +26,23 @@ export class TelegramAdapter extends ChannelAdapter {
async start(): Promise<void> {
this.bot = new Bot(this.telegramConfig.botToken)
// Middleware: only accept messages from configured chatId
// Global error handler — prevent unhandled errors from crashing the bot
this.bot.catch((err) => {
log.error('Bot error:', err.message || err)
})
// Ensure allowed_updates includes callback_query on every poll
this.bot.api.config.use((prev, method, payload, signal) => {
if (method === 'getUpdates') {
(payload as any).allowed_updates = (payload as any).allowed_updates ?? ['message', 'callback_query']
}
return prev(method, payload, signal)
})
// Middleware: only accept updates from configured chatId
this.bot.use((ctx, next) => {
if (ctx.chat?.id !== this.telegramConfig.chatId) return
const chatId = ctx.chat?.id ?? ctx.callbackQuery?.message?.chat?.id
if (chatId !== this.telegramConfig.chatId) return
return next()
})
@ -101,19 +115,19 @@ export class TelegramAdapter extends ChannelAdapter {
// Notification topic → ignore
if (threadId === this.notificationTopicId) return
// Assistant topic → forward to assistant session
// Assistant topic → forward to assistant session (fire-and-forget)
if (threadId === this.assistantTopicId) {
await handleAssistantMessage(this.assistantSession, ctx.message.text)
handleAssistantMessage(this.assistantSession, ctx.message.text).catch(err => log.error('Assistant error:', err))
return
}
// Session topic → forward to core
await (this.core as OpenACPCore).handleMessage({
// Session topic → forward to core (fire-and-forget to avoid blocking polling)
;(this.core as OpenACPCore).handleMessage({
channelId: 'telegram',
threadId: String(threadId),
userId: String(ctx.from.id),
text: ctx.message.text,
})
}).catch(err => log.error('handleMessage error:', err))
})
}
@ -143,23 +157,27 @@ export class TelegramAdapter extends ChannelAdapter {
case 'tool_call': {
await this.finalizeDraft(sessionId)
const meta = content.metadata as any
const msg = await this.bot.api.sendMessage(this.telegramConfig.chatId,
formatToolCall(content.metadata as any),
formatToolCall(meta),
{ message_thread_id: threadId, parse_mode: 'HTML', disable_notification: true }
)
if (!this.toolCallMessages.has(sessionId)) {
this.toolCallMessages.set(sessionId, new Map())
}
this.toolCallMessages.get(sessionId)!.set(content.metadata?.id as string, msg.message_id)
this.toolCallMessages.get(sessionId)!.set(meta.id, { msgId: msg.message_id, name: meta.name, kind: meta.kind })
break
}
case 'tool_update': {
const msgId = this.toolCallMessages.get(sessionId)?.get(content.metadata?.id as string)
if (msgId) {
const meta = content.metadata as any
const toolState = this.toolCallMessages.get(sessionId)?.get(meta.id)
if (toolState) {
// Merge name/kind from original tool_call
const merged = { ...meta, name: meta.name || toolState.name, kind: meta.kind || toolState.kind }
try {
await this.bot.api.editMessageText(this.telegramConfig.chatId, msgId,
formatToolUpdate(content.metadata as any),
await this.bot.api.editMessageText(this.telegramConfig.chatId, toolState.msgId,
formatToolUpdate(merged),
{ parse_mode: 'HTML' }
)
} catch { /* edit failed */ }

View File

@ -55,34 +55,68 @@ export function markdownToTelegramHtml(md: string): string {
return text
}
export function formatToolCall(tool: { id: string; name?: string; kind?: string; status?: string }): string {
const statusIcon: Record<string, string> = {
pending: '⏳',
in_progress: '⏳',
completed: '✅',
failed: '❌',
}
const kindIcon: Record<string, string> = {
read: '📄', edit: '✏️', delete: '🗑️', execute: '⚡',
search: '🔍', fetch: '🌐', think: '💭',
}
const si = statusIcon[tool.status || ''] || '🔧'
const ki = kindIcon[tool.kind || ''] || '🔧'
return `${ki} ${si} <b>${escapeHtml(tool.name || 'Tool')}</b>`
const STATUS_ICON: Record<string, string> = {
pending: '⏳',
in_progress: '🔄',
completed: '✅',
failed: '❌',
}
export function formatToolUpdate(update: { id: string; status: string; content?: unknown }): string {
const statusIcon: Record<string, string> = {
pending: '⏳',
in_progress: '⏳',
completed: '✅',
failed: '❌',
const KIND_ICON: Record<string, string> = {
read: '📖', edit: '✏️', delete: '🗑️', execute: '▶️',
search: '🔍', fetch: '🌐', think: '🧠', move: '📦', other: '🛠️',
}
function extractContentText(content: unknown): string {
if (!content) return ''
if (typeof content === 'string') return content
if (Array.isArray(content)) {
return content
.map((c: any) => extractContentText(c))
.filter(Boolean)
.join('\n')
}
const si = statusIcon[update.status] || '🔧'
let text = `${si} <b>Tool ${update.status}</b>`
if (update.content) {
const contentStr = typeof update.content === 'string' ? update.content : JSON.stringify(update.content)
text += `\n<pre>${escapeHtml(contentStr)}</pre>`
if (typeof content === 'object' && content !== null) {
const c = content as any
// ACP content blocks: {type: ..., text: ...} or {type: ..., content: ...}
if (c.type === 'text' && typeof c.text === 'string') return c.text
if (typeof c.text === 'string') return c.text
if (typeof c.content === 'string') return c.content
// Tool input/output objects
if (c.input) return extractContentText(c.input)
if (c.output) return extractContentText(c.output)
// Fallback: pretty-print JSON (but skip type-only objects)
const keys = Object.keys(c).filter(k => k !== 'type')
if (keys.length === 0) return ''
return JSON.stringify(c, null, 2)
}
return String(content)
}
function truncateContent(text: string, maxLen = 3800): string {
if (text.length <= maxLen) return text
return text.slice(0, maxLen) + '\n… (truncated)'
}
export function formatToolCall(tool: { id: string; name?: string; kind?: string; status?: string; content?: unknown }): string {
const si = STATUS_ICON[tool.status || ''] || '🔧'
const ki = KIND_ICON[tool.kind || ''] || '🛠️'
let text = `${si} ${ki} <b>${escapeHtml(tool.name || 'Tool')}</b>`
const details = extractContentText(tool.content)
if (details) {
text += `\n<pre>${escapeHtml(truncateContent(details))}</pre>`
}
return text
}
export function formatToolUpdate(update: { id: string; name?: string; kind?: string; status: string; content?: unknown }): string {
const si = STATUS_ICON[update.status] || '🔧'
const ki = KIND_ICON[update.kind || ''] || '🛠️'
const name = update.name || 'Tool'
let text = `${si} ${ki} <b>${escapeHtml(name)}</b>`
const details = extractContentText(update.content)
if (details) {
text += `\n<pre>${escapeHtml(truncateContent(details))}</pre>`
}
return text
}

View File

@ -70,7 +70,10 @@ export class PermissionHandler {
const [, callbackKey, optionId] = parts
const pending = this.pending.get(callbackKey)
if (!pending) return
if (!pending) {
try { await ctx.answerCallbackQuery({ text: '❌ Expired' }) } catch { /* old query */ }
return
}
const session = this.getSession(pending.sessionId)
if (session?.pendingPermission?.requestId === pending.requestId) {
@ -79,7 +82,7 @@ export class PermissionHandler {
}
this.pending.delete(callbackKey)
await ctx.answerCallbackQuery({ text: '✅ Responded' })
try { await ctx.answerCallbackQuery({ text: '✅ Responded' }) } catch { /* old query */ }
// Remove buttons
try {

View File

@ -183,6 +183,7 @@ export class AgentInstance {
name: update.title,
kind: update.kind ?? undefined,
status: update.status ?? 'pending',
content: update.content ?? undefined,
}
break
case 'tool_call_update':
@ -190,6 +191,7 @@ export class AgentInstance {
type: 'tool_update',
id: update.toolCallId,
status: update.status ?? 'pending',
content: update.content ?? undefined,
}
break
case 'plan':

View File

@ -190,21 +190,16 @@ export class OpenACPCore {
}
session.agentInstance.onPermissionRequest = async (request: PermissionRequest) => {
// Send permission UI to session topic
await adapter.sendPermissionRequest(session.id, request)
// Send notification with deep link
await this.notificationManager.notify(session.channelId, {
sessionId: session.id,
sessionName: session.name,
type: 'permission',
summary: request.description,
})
// Wait for user response — adapter resolves this promise
return new Promise<string>((resolve) => {
// Set pending BEFORE sending UI to avoid race condition
const promise = new Promise<string>((resolve) => {
session.pendingPermission = { requestId: request.id, resolve }
})
// Send permission UI to session topic (notification is sent by adapter)
await adapter.sendPermissionRequest(session.id, request)
// Wait for user response — adapter resolves this promise
return promise
}
}
}