🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
improve discord interaction
arvinxxdd0d4d889006
diff --git a/src/app/(backend)/api/agent/webhooks/bot-callback/route.ts b/src/app/(backend)/api/agent/webhooks/bot-callback/route.tsindex 83973118987..64aec0343c1 100644--- a/src/app/(backend)/api/agent/webhooks/bot-callback/route.ts+++ b/src/app/(backend)/api/agent/webhooks/bot-callback/route.ts@@ -45,7 +45,7 @@ export async function POST(request: Request): Promise<Response> {const body = JSON.parse(rawBody);- const { type, applicationId, platformThreadId, progressMessageId } = body;+ const { type, applicationId, platformThreadId, progressMessageId, userMessageId } = body;log('bot-callback: parsed body keys=%s, type=%s, applicationId=%s, platformThreadId=%s, progressMessageId=%s',@@ -103,6 +103,15 @@ export async function POST(request: Request): Promise<Response> {await handleStepCallback(body, discord, channelId, progressMessageId);} else if (type === 'completion') {await handleCompletionCallback(body, discord, channelId, progressMessageId);++ // Remove eyes reaction from the original user message+ if (userMessageId) {+ try {+ await discord.removeOwnReaction(channelId, userMessageId, '👀');+ } catch (error) {+ log('bot-callback: failed to remove eyes reaction: %O', error);+ }+ }} else {return NextResponse.json({ error: `Unknown callback type: ${type}` }, { status: 400 });}@@ -145,8 +154,15 @@ async function handleStepCallback(totalToolCalls: body.totalToolCalls,});+ // If the LLM returned text without tool calls, the next step is 'finish' — skip typing+ const isLlmFinalResponse =+ body.stepType === 'call_llm' && !body.toolsCalling?.length && body.content;+try {await discord.editMessage(channelId, progressMessageId, progressText);+ if (!isLlmFinalResponse) {+ await discord.triggerTyping(channelId);+ }} catch (error) {log('handleStepCallback: failed to edit progress message: %O', error);}diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex c50af2339a8..28869ebcc8c 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -577,42 +577,51 @@ export class AgentRuntimeService {const toolNames = mappedResults.map((r) => `${r.identifier}/${r.apiName}`);stepSummary = `[tools×${toolCount}] ${toolNames.join(', ')}`;} else {- // LLM result- const llmEvent = stepResult.events?.find((e) => e.type === 'llm_result');- content = (llmEvent as any)?.result?.content || undefined;- reasoning = (llmEvent as any)?.result?.reasoning || undefined;-- // Use parsed ChatToolPayload from payload (has identifier + apiName)- const payloadToolsCalling = (stepResult.nextContext?.payload as any)?.toolsCalling as- | Array<{ apiName: string; arguments: string; identifier: string }>+ // Check for done event first (finish step with no next context)+ const doneEvent = stepResult.events?.find((e) => e.type === 'done') as+ | { reason?: string; reasonDetail?: string; type: 'done' }| undefined;- const hasToolCalls = Array.isArray(payloadToolsCalling) && payloadToolsCalling.length > 0;-- if (hasToolCalls) {- toolsCalling = payloadToolsCalling.map((tc) => ({- apiName: tc.apiName,- arguments: tc.arguments,- identifier: tc.identifier,- }));- }- const parts: string[] = [];- if (reasoning) {- const thinkPreview = reasoning.length > 30 ? reasoning.slice(0, 30) + '...' : reasoning;- parts.push(`💭 "${thinkPreview}"`);- }- if (!content && hasToolCalls) {- parts.push(- `→ call tools: ${toolsCalling!.map((tc) => `${tc.identifier}|${tc.apiName}`).join(', ')}`,- );- } else if (content) {- const preview = content.length > 20 ? content.slice(0, 20) + '...' : content;- parts.push(`"${preview}"`);- }- if (parts.length > 0) {- stepSummary = `[llm] ${parts.join(' | ')}`;+ if (doneEvent) {+ stepSummary = `[done] reason=${doneEvent.reason ?? 'unknown'}`;} else {- stepSummary = `[llm] (empty) result: ${JSON.stringify(stepResult, null, 2)}`;+ // LLM result+ const llmEvent = stepResult.events?.find((e) => e.type === 'llm_result');+ content = (llmEvent as any)?.result?.content || undefined;+ reasoning = (llmEvent as any)?.result?.reasoning || undefined;++ // Use parsed ChatToolPayload from payload (has identifier + apiName)+ const payloadToolsCalling = (stepResult.nextContext?.payload as any)?.toolsCalling as+ | Array<{ apiName: string; arguments: string; identifier: string }>+ | undefined;+ const hasToolCalls = Array.isArray(payloadToolsCalling) && payloadToolsCalling.length > 0;++ if (hasToolCalls) {+ toolsCalling = payloadToolsCalling.map((tc) => ({+ apiName: tc.apiName,+ arguments: tc.arguments,+ identifier: tc.identifier,+ }));+ }++ const parts: string[] = [];+ if (reasoning) {+ const thinkPreview = reasoning.length > 30 ? reasoning.slice(0, 30) + '...' : reasoning;+ parts.push(`💭 "${thinkPreview}"`);+ }+ if (!content && hasToolCalls) {+ parts.push(+ `→ call tools: ${toolsCalling!.map((tc) => `${tc.identifier}|${tc.apiName}`).join(', ')}`,+ );+ } else if (content) {+ const preview = content.length > 20 ? content.slice(0, 20) + '...' : content;+ parts.push(`"${preview}"`);+ }+ if (parts.length > 0) {+ stepSummary = `[llm] ${parts.join(' | ')}`;+ } else {+ stepSummary = `[llm] (empty) phase=${stepResult.nextContext?.phase ?? 'none'} events=${stepResult.events?.length ?? 0}`;+ }}}@@ -704,12 +713,12 @@ export class AgentRuntimeService {stepResult.newState.metadata._stepTracking = updatedTracking;await this.coordinator.saveAgentState(operationId, stepResult.newState);- // Fire step webhook- await this.triggerStepWebhook(- stepResult.newState,- operationId,- stepPresentationData as unknown as Record<string, unknown>,- );+ // Fire step webhook (include shouldContinue so the callback knows+ // whether the agent is still running or about to complete)+ await this.triggerStepWebhook(stepResult.newState, operationId, {+ ...stepPresentationData,+ shouldContinue,+ } as unknown as Record<string, unknown>);}if (shouldContinue && stepResult.nextContext && this.queueService) {diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.tsindex 203d3b0bbe8..800459191af 100644--- a/src/server/services/bot/AgentBridgeService.ts+++ b/src/server/services/bot/AgentBridgeService.ts@@ -113,6 +113,8 @@ export class AgentBridgeService {await thread.subscribe();await thread.startTyping();+ const queueMode = isQueueAgentRuntimeEnabled();+try {// executeWithCallback handles progress message (post + edit at each step)// The final reply is edited into the progress message by onComplete@@ -132,8 +134,10 @@ export class AgentBridgeService {const msg = error instanceof Error ? error.message : String(error);await thread.post(`**Agent Execution Failed**\n\`\`\`\n${msg}\n\`\`\``);} finally {- // Always clean up reactions- await this.removeReceivedReaction(thread, message);+ // In queue mode, reaction is removed by the bot-callback webhook on completion+ if (!queueMode) {+ await this.removeReceivedReaction(thread, message);+ }}}@@ -156,6 +160,8 @@ export class AgentBridgeService {return this.handleMention(thread, message, { agentId, botContext });}+ const queueMode = isQueueAgentRuntimeEnabled();+// Immediate feedback: mark as received + show typingawait safeReaction(() => thread.adapter.addReaction(thread.id, message.id, RECEIVED_EMOJI),@@ -176,7 +182,10 @@ export class AgentBridgeService {const msg = error instanceof Error ? error.message : String(error);await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${msg}\n\`\`\``);} finally {- await this.removeReceivedReaction(thread, message);+ // In queue mode, reaction is removed by the bot-callback webhook on completion+ if (!queueMode) {+ await this.removeReceivedReaction(thread, message);+ }}}@@ -232,6 +241,10 @@ export class AgentBridgeService {throw new Error('Failed to post initial progress message');}+ // Refresh typing indicator after posting the ack message,+ // so typing stays active until the first step webhook arrives+ await thread.startTyping();+// Build webhook URL for bot-callback endpoint// Prefer INTERNAL_APP_URL for server-to-server calls (bypasses CDN/proxy)const baseURL = appEnv.INTERNAL_APP_URL || appEnv.APP_URL;@@ -245,6 +258,7 @@ export class AgentBridgeService {applicationId: botContext?.applicationId,platformThreadId: botContext?.platformThreadId,progressMessageId,+ userMessageId: userMessage.id,};log(diff --git a/src/server/services/bot/__tests__/replyTemplate.test.ts b/src/server/services/bot/__tests__/replyTemplate.test.tsindex 518ede9e2ce..83167ad63f7 100644--- a/src/server/services/bot/__tests__/replyTemplate.test.ts+++ b/src/server/services/bot/__tests__/replyTemplate.test.ts@@ -1,4 +1,3 @@-import { emoji } from 'chat';import { describe, expect, it } from 'vitest';import type { RenderStepParams } from '../replyTemplate';@@ -134,7 +133,7 @@ describe('replyTemplate', () => {thinking: false,}),),- ).toBe(`${emoji.thinking} Let me think about this...`);+ ).toBe(`💭 Let me think about this...`);});it('should show content with processing when pure text', () => {@@ -149,9 +148,7 @@ describe('replyTemplate', () => {});it('should show processing fallback when no content at all', () => {- expect(renderLLMGenerating(makeParams({ thinking: false }))).toBe(- `${emoji.thinking} Processing...`,- );+ expect(renderLLMGenerating(makeParams({ thinking: false }))).toBe(`💭 Processing...`);});});@@ -173,7 +170,7 @@ describe('replyTemplate', () => {}),),).toBe(- `I will search for that.\n\n⏺ **builtin·web_search**(query: "test")\n ⎿ Found 3 results\n\n${emoji.thinking} Processing...`,+ `I will search for that.\n\n⏺ **builtin·web_search**(query: "test")\n ⎿ success:15 chars\n\n💭 Processing...`,);});@@ -186,7 +183,7 @@ describe('replyTemplate', () => {toolsResult: [{ apiName: 'get_time', identifier: 'builtin' }],}),),- ).toBe(`⏺ **builtin·get_time**\n\n${emoji.thinking} Processing...`);+ ).toBe(`⏺ **builtin·get_time**\n\n💭 Processing...`);});it('should show multiple completed tools with results', () => {@@ -213,7 +210,7 @@ describe('replyTemplate', () => {}),),).toBe(- `⏺ **builtin·search**(q: "test")\n ⎿ Found 5 results\n⏺ **lobe-web-browsing·readUrl**(url: "https://example.com")\n ⎿ Page loaded successfully\n\n${emoji.thinking} Processing...`,+ `⏺ **builtin·search**(q: "test")\n ⎿ success:15 chars\n⏺ **lobe-web-browsing·readUrl**(url: "https://example.com")\n ⎿ success:24 chars\n\n💭 Processing...`,);});@@ -225,13 +222,11 @@ describe('replyTemplate', () => {stepType: 'call_tool',}),),- ).toBe(`I found some results.\n\n${emoji.thinking} Processing...`);+ ).toBe(`I found some results.\n\n💭 Processing...`);});it('should show processing fallback when no lastContent and no tools', () => {- expect(renderToolExecuting(makeParams({ stepType: 'call_tool' }))).toBe(- `${emoji.thinking} Processing...`,- );+ expect(renderToolExecuting(makeParams({ stepType: 'call_tool' }))).toBe(`💭 Processing...`);});});@@ -241,23 +236,20 @@ describe('replyTemplate', () => {it('should return undefined for empty output', () => {expect(summarizeOutput(undefined)).toBeUndefined();expect(summarizeOutput('')).toBeUndefined();+ expect(summarizeOutput(' ')).toBeUndefined();});- it('should return first line for single-line output', () => {- expect(summarizeOutput('Hello world')).toBe('Hello world');- });-- it('should truncate long first line', () => {- const long = 'a'.repeat(120);- expect(summarizeOutput(long)).toBe('a'.repeat(100) + '...');+ it('should show char count for output', () => {+ expect(summarizeOutput('Hello world')).toBe('success:11 chars');});- it('should show line count for multi-line output', () => {- expect(summarizeOutput('line1\nline2\nline3')).toBe('line1 … +2 lines');+ it('should show char count for long output', () => {+ const long = 'a'.repeat(5000);+ expect(summarizeOutput(long)).toContain('5,000 chars');});- it('should skip blank lines', () => {- expect(summarizeOutput('line1\n\n\nline2')).toBe('line1 … +1 lines');+ it('should show char count for multi-line output', () => {+ expect(summarizeOutput('line1\nline2\nline3')).toBe('success:17 chars');});});@@ -387,7 +379,7 @@ describe('replyTemplate', () => {}),),).toBe(- `Previous content\n\n⏺ **builtin·search**(q: "test")\n ⎿ Found results\n\n${emoji.thinking} Processing...`,+ `Previous content\n\n⏺ **builtin·search**(q: "test")\n ⎿ success:13 chars\n\n💭 Processing...`,);});});diff --git a/src/server/services/bot/discordRestApi.ts b/src/server/services/bot/discordRestApi.tsindex f1f494a8c71..3a9d43cfbf6 100644--- a/src/server/services/bot/discordRestApi.ts+++ b/src/server/services/bot/discordRestApi.ts@@ -16,6 +16,18 @@ export class DiscordRestApi {await this.rest.patch(Routes.channelMessage(channelId, messageId), { body: { content } });}+ async triggerTyping(channelId: string): Promise<void> {+ log('triggerTyping: channel=%s', channelId);+ await this.rest.post(Routes.channelTyping(channelId));+ }++ async removeOwnReaction(channelId: string, messageId: string, emoji: string): Promise<void> {+ log('removeOwnReaction: channel=%s, message=%s, emoji=%s', channelId, messageId, emoji);+ await this.rest.delete(+ Routes.channelMessageOwnReaction(channelId, messageId, encodeURIComponent(emoji)),+ );+ }+async createMessage(channelId: string, content: string): Promise<{ id: string }> {log('createMessage: channel=%s', channelId);const data = (await this.rest.post(Routes.channelMessages(channelId), {diff --git a/src/server/services/bot/replyTemplate.ts b/src/server/services/bot/replyTemplate.tsindex 650de47f119..146505fb4c5 100644--- a/src/server/services/bot/replyTemplate.ts+++ b/src/server/services/bot/replyTemplate.ts@@ -1,8 +1,12 @@-import { emoji } from 'chat';-import type { StepPresentationData } from '../agentRuntime/types';import { getExtremeAck } from './ackPhrases';+// Use raw Unicode emoji instead of Chat SDK emoji placeholders,+// because bot-callback webhooks send via DiscordRestApi directly+// (not through the Chat SDK adapter that resolves placeholders).+const EMOJI_THINKING = '💭';+const EMOJI_SUCCESS = '✅';+// ==================== Message Splitting ====================const DEFAULT_CHAR_LIMIT = 1800;@@ -68,17 +72,13 @@ function formatToolCall(tc: ToolCallItem): string {return formatToolName(tc);}-export function summarizeOutput(output: string | undefined, maxLength = 100): string | undefined {+export function summarizeOutput(output: string | undefined): string | undefined {if (!output) return undefined;- const lines = output.split('\n').filter((l) => l.trim());- if (lines.length === 0) return undefined;+ const trimmed = output.trim();+ if (trimmed.length === 0) return undefined;- const firstLine = lines[0].length > maxLength ? lines[0].slice(0, maxLength) + '...' : lines[0];-- if (lines.length > 1) {- return `${firstLine} … +${lines.length - 1} lines`;- }- return firstLine;+ const chars = trimmed.length;+ return `success: ${chars.toLocaleString()} chars`;}function formatPendingTools(toolsCalling: ToolCallItem[]): string {@@ -178,7 +178,7 @@ export function renderLLMGenerating(params: RenderStepParams): string {// Sub-state: has reasoning (thinking)if (reasoning && !content) {- return `${header}${emoji.thinking} ${reasoning}${footer}`;+ return `${header}${EMOJI_THINKING} ${reasoning}${footer}`;}// Sub-state: pure text content (waiting for next step)@@ -186,7 +186,7 @@ export function renderLLMGenerating(params: RenderStepParams): string {return `${header}${displayContent}\n\n${footer}`;}- return `${header}${emoji.thinking} Processing...${footer}`;+ return `${header}${EMOJI_THINKING} Processing...${footer}`;}// ==================== 3. Tool Executing ====================@@ -220,9 +220,9 @@ export function renderToolExecuting(params: RenderStepParams): string {if (lastToolsCalling && lastToolsCalling.length > 0) {parts.push(formatCompletedTools(lastToolsCalling, toolsResult));- parts.push(`${emoji.thinking} Processing...`);+ parts.push(`${EMOJI_THINKING} Processing...`);} else {- parts.push(`${emoji.thinking} Processing...`);+ parts.push(`${EMOJI_THINKING} Processing...`);}return parts.join('\n\n') + footer;