Skip to content

🀯 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.

Add /new and /stop slash commands for bot message management (#13194)

Rdmclin2f853537695f0
diff --git a/src/server/routers/lambda/__tests__/aiAgent.interruptTask.test.ts b/src/server/routers/lambda/__tests__/aiAgent.interruptTask.test.ts
index c8089addcde..ebf0888a97d 100644
--- a/src/server/routers/lambda/__tests__/aiAgent.interruptTask.test.ts
+++ b/src/server/routers/lambda/__tests__/aiAgent.interruptTask.test.ts
@@ -15,10 +15,12 @@ vi.mock('@/database/core/db-adaptor', () => ({
getServerDB: vi.fn(() => testDB),
}));
-// Mock AgentRuntimeService - interruptOperation method doesn't exist yet
+const mockInterruptOperation = vi.fn();
+
+// Mock AgentRuntimeService
vi.mock('@/server/services/agentRuntime', () => ({
AgentRuntimeService: vi.fn().mockImplementation(() => ({
- // No interruptOperation method - tests the graceful fallback
+ interruptOperation: mockInterruptOperation,
})),
}));
@@ -39,6 +41,8 @@ describe('aiAgentRouter.interruptTask', () => {
serverDB = await getTestDB();
testDB = serverDB;
userId = await createTestUser(serverDB);
+ mockInterruptOperation.mockReset();
+ mockInterruptOperation.mockResolvedValue(true);
// Create test agent
const [agent] = await serverDB
@@ -201,25 +205,27 @@ describe('aiAgentRouter.interruptTask', () => {
});
});
- describe('graceful handling without interruptOperation method', () => {
- it('should succeed even when interruptOperation method is not available', async () => {
- // The mock doesn't have interruptOperation method
- // This tests the graceful fallback in the implementation
+ describe('interrupt failure handling', () => {
+ it('should return success=false and keep thread processing when runtime interrupt fails', async () => {
+ mockInterruptOperation.mockResolvedValue(false);
+
const caller = aiAgentRouter.createCaller(createTestContext());
const result = await caller.interruptTask({
threadId: testThreadId,
});
- // Should still succeed and update thread status
- expect(result.success).toBe(true);
+ expect(result.success).toBe(false);
+ expect(result.threadId).toBe(testThreadId);
+ expect(result.operationId).toBe('op-interrupt-test');
const [updatedThread] = await serverDB
.select()
.from(threads)
.where(eq(threads.id, testThreadId));
- expect(updatedThread.status).toBe(ThreadStatus.Cancel);
+ expect(updatedThread.status).toBe(ThreadStatus.Processing);
+ expect(updatedThread.metadata?.completedAt).toBeUndefined();
});
});
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
index 2ddc546aa01..ee5c01f824a 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
@@ -5,6 +5,7 @@ import type * as ModelBankModule from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentRuntimeService } from './AgentRuntimeService';
+import { hookDispatcher } from './hooks';
import {
type AgentExecutionParams,
type OperationCreationParams,
@@ -93,7 +94,7 @@ vi.mock('@/server/modules/AgentRuntime', async (importOriginal) => {
});
vi.mock('@lobechat/agent-runtime', () => ({
- AgentRuntime: vi.fn().mockImplementation((agent, options) => ({
+ AgentRuntime: vi.fn().mockImplementation((_agent, _options) => ({
step: vi.fn(),
})),
}));
@@ -180,6 +181,7 @@ describe('AgentRuntimeService', () => {
afterEach(() => {
delete process.env.AGENT_RUNTIME_BASE_URL;
+ hookDispatcher.unregister('test-operation-1');
});
describe('constructor', () => {
@@ -310,6 +312,52 @@ describe('AgentRuntimeService', () => {
}),
);
});
+
+ it('should abort before creating operation when signal is already aborted', async () => {
+ const controller = new AbortController();
+ controller.abort(new Error('startup aborted'));
+
+ await expect(
+ service.createOperation({
+ ...mockParams,
+ signal: controller.signal,
+ }),
+ ).rejects.toMatchObject({
+ message: 'startup aborted',
+ name: 'AbortError',
+ });
+
+ expect(mockCoordinator.createAgentOperation).not.toHaveBeenCalled();
+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();
+ });
+
+ it('should cleanup partially created operation when aborted before scheduling', async () => {
+ const controller = new AbortController();
+ const originalCreateAgentOperation =
+ mockCoordinator.createAgentOperation.getMockImplementation();
+
+ mockCoordinator.createAgentOperation.mockImplementationOnce(async (...args: any[]) => {
+ await originalCreateAgentOperation?.(...args);
+ controller.abort(new Error('startup aborted'));
+ });
+
+ await expect(
+ service.createOperation({
+ ...mockParams,
+ hooks: [{ handler: vi.fn(), id: 'hook-1', type: 'onComplete' }],
+ signal: controller.signal,
+ stepCallbacks: { onComplete: vi.fn() },
+ }),
+ ).rejects.toMatchObject({
+ message: 'startup aborted',
+ name: 'AbortError',
+ });
+
+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();
+ expect(mockCoordinator.deleteAgentOperation).toHaveBeenCalledWith('test-operation-1');
+ expect(service.getStepCallbacks('test-operation-1')).toBeUndefined();
+ expect(hookDispatcher.hasHooks('test-operation-1')).toBe(false);
+ });
});
describe('executeStep', () => {
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 525aa61c380..6333286616c 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -21,6 +21,7 @@ import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
import { ToolExecutionService } from '@/server/services/toolExecution';
import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';
+import { isAbortError, throwIfAborted } from './abort';
import { hookDispatcher } from './hooks';
import {
type AgentExecutionParams,
@@ -279,12 +280,18 @@ export class AgentRuntimeService {
userMemory,
deviceSystemInfo,
skillMetas,
+ signal,
userTimezone,
} = params;
const operationToolSet = toolSet;
+ let operationCreated = false;
+ let stepCallbacksRegistered = false;
+ let hooksRegistered = false;
try {
+ throwIfAborted(signal, 'Agent execution aborted before operation startup');
+
const memories = userMemory?.memories;
log(
'[%s] Creating new operation (autoStart: %s) with params: model=%s, provider=%s, tools=%d, messages=%d, manifests=%d, memory=%s',
@@ -348,6 +355,7 @@ export class AgentRuntimeService {
modelRuntimeConfig,
userId,
});
+ operationCreated = true;
// Save initial state
await this.coordinator.saveAgentState(operationId, initialState as any);
@@ -355,11 +363,13 @@ export class AgentRuntimeService {
// Register step lifecycle callbacks
if (stepCallbacks) {
this.registerStepCallbacks(operationId, stepCallbacks);
+ stepCallbacksRegistered = true;
}
// Register external hooks
if (hooks && hooks.length > 0) {
hookDispatcher.register(operationId, hooks);
+ hooksRegistered = true;
// Persist webhook configs to state metadata for production mode
const serializedHooks = hookDispatcher.getSerializedHooks(operationId);
@@ -377,6 +387,8 @@ export class AgentRuntimeService {
}
}
+ throwIfAborted(signal, 'Agent execution aborted before first step scheduling');
+
let messageId: string | undefined;
let autoStarted = false;
@@ -402,6 +414,27 @@ export class AgentRuntimeService {
return { autoStarted, messageId, operationId, success: true };
} catch (error) {
+ if (isAbortError(error)) {
+ if (stepCallbacksRegistered) {
+ this.unregisterStepCallbacks(operationId);
+ }
+
+ if (hooksRegistered) {
+ hookDispatcher.unregister(operationId);
+ }
+
+ if (operationCreated) {
+ try {
+ await this.coordinator.deleteAgentOperation(operationId);
+ } catch (cleanupError) {
+ console.error('Failed to cleanup aborted operation %s: %O', operationId, cleanupError);
+ }
+ }
+
+ log('[%s] Operation creation aborted before scheduling', operationId);
+ throw error;
+ }
+
console.error('Failed to create operation %s: %O', operationId, error);
throw error;
}
diff --git a/src/server/services/agentRuntime/abort.ts b/src/server/services/agentRuntime/abort.ts
new file mode 100644
index 00000000000..626ba65c81b
--- /dev/null
+++ b/src/server/services/agentRuntime/abort.ts
@@ -0,0 +1,32 @@
+const DEFAULT_ABORT_MESSAGE = 'Agent execution aborted';
+
+export function createAbortError(message = DEFAULT_ABORT_MESSAGE): Error {
+ const error = new Error(message);
+ error.name = 'AbortError';
+ return error;
+}
+
+export function getAbortError(signal?: AbortSignal, message = DEFAULT_ABORT_MESSAGE): Error {
+ const reason = signal?.reason;
+
+ if (reason instanceof Error) {
+ if (reason.name === 'AbortError') return reason;
+ return createAbortError(reason.message || message);
+ }
+
+ if (typeof reason === 'string' && reason.length > 0) {
+ return createAbortError(reason);
+ }
+
+ return createAbortError(message);
+}
+
+export function throwIfAborted(signal?: AbortSignal, message = DEFAULT_ABORT_MESSAGE): void {
+ if (!signal?.aborted) return;
+
+ throw getAbortError(signal, message);
+}
+
+export function isAbortError(error: unknown): error is Error {
+ return error instanceof Error && error.name === 'AbortError';
+}
diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.ts
index da9a4eec346..9e72dc39a67 100644
--- a/src/server/services/agentRuntime/types.ts
+++ b/src/server/services/agentRuntime/types.ts
@@ -164,6 +164,8 @@ export interface OperationCreationParams {
maxSteps?: number;
modelRuntimeConfig?: any;
operationId: string;
+ /** Abort startup before the first step is scheduled */
+ signal?: AbortSignal;
/** Skill metas for <available_skills> prompt injection */
skillMetas?: Array<{ description: string; identifier: string; name: string }>;
/**
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 2cad68782b5..6da1b13af8e 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -43,6 +43,7 @@ import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngin
import { AgentService } from '@/server/services/agent';
import type { AgentRuntimeServiceOptions } from '@/server/services/agentRuntime';
import { AgentRuntimeService } from '@/server/services/agentRuntime';
+import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';
import { type AgentHook } from '@/server/services/agentRuntime/hooks/types';
import { type StepLifecycleCallbacks } from '@/server/services/agentRuntime/types';
import { FileService } from '@/server/services/file';
@@ -108,6 +109,8 @@ interface InternalExecAgentParams extends ExecAgentParams {
hooks?: AgentHook[];
/** Maximum steps for the agent operation */
maxSteps?: number;
+ /** Abort startup before the agent runtime operation is created */
+ signal?: AbortSignal;
/** Step lifecycle callbacks for operation tracking (server-side only) */
stepCallbacks?: StepLifecycleCallbacks;
/**
@@ -216,6 +219,7 @@ export class AiAgentService {
cronJobId,
evalContext,
maxSteps,
+ signal,
userInterventionConfig,
completionWebhook,
stepWebhook,
@@ -232,6 +236,39 @@ export class AiAgentService {
log('execAgent: identifier=%s, prompt=%s', identifier, prompt.slice(0, 50));
+ const assistantMessageRef: { current?: string } = {};
+ const updateAbortedAssistantMessage = async (errorMessage: string) => {
+ if (!assistantMessageRef.current) return;
+
+ try {
+ await this.messageModel.update(assistantMessageRef.current, {
+ content: '',
+ error: {
+ body: {
+ detail: errorMessage,
+ },
+ message: errorMessage,
+ type: 'ServerAgentRuntimeError',
+ },
+ });
+ } catch (error) {
+ log(
+ 'execAgent: failed to update aborted assistant message %s: %O',
+ assistantMessageRef.current,
+ error,
+ );
+ }
+ };
+ const throwIfExecutionAborted = async (stage: string) => {
+ if (!signal?.aborted) return;
+
+ const error = getAbortError(signal, `Agent execution aborted during ${stage}`);
+ await updateAbortedAssistantMessage(error.message);
+ throw error;
+ };
+
+ throwIfAborted(signal, 'Agent execution aborted before startup');
+
// 1. Get agent configuration with default config merged (supports both id and slug)
const agentConfig = await this.agentService.getAgentConfig(identifier);
if (!agentConfig) {
@@ -272,6 +309,8 @@ export class AiAgentService {
}
}
+ await throwIfExecutionAborted('agent configuration');
+
// 2.5. Append additional instructions to agent's systemRole
if (instructions) {
agentConfig.systemRole = agentConfig.systemRole
@@ -307,6 +346,8 @@ export class AiAgentService {
log('execAgent: reusing existing topic %s', topicId);
}
+ await throwIfExecutionAborted('topic setup');
+
// Extract model and provider from agent config
const model = agentConfig.model!;
const provider = agentConfig.provider!;
@@ -363,6 +404,8 @@ export class AiAgentService {
userTimezone ?? 'default',
);
+ await throwIfExecutionAborted('tool discovery');
+
// 9. Create tools using Server AgentToolsEngine
const hasEnabledKnowledgeBases =
agentConfig.knowledgeBases?.some((kb: { enabled?: boolean | null }) => kb.enabled === true) ??
@@ -605,6 +648,8 @@ export class AiAgentService {
);
}
+ await throwIfExecutionAborted('tool preparation');
+
// 10. Fetch user persona for memory injection (reuses globalMemoryEnabled from step 8)
let userMemory: ServerUserMemoryConfig | undefined;
@@ -650,6 +695,8 @@ export class AiAgentService {
});
}
+ await throwIfExecutionAborted('message history loading');
+
// 12. Upload external files to S3 and collect file IDs
let fileIds: string[] | undefined;
let imageList: Array<{ alt: string; id: string; url: string }> | undefined;
@@ -660,6 +707,8 @@ export class AiAgentService {
imageList = [];
for (const file of files) {
+ await throwIfExecutionAborted('file upload');
+
const ext = file.name?.split('.').pop() || 'bin';
const pathname = `files/${this.userId}/${nanoid()}/${file.name || `file.${ext}`}`;
@@ -683,6 +732,8 @@ export class AiAgentService {
if (imageList.length === 0) imageList = undefined;
}
+ await throwIfExecutionAborted('message creation');
+
// 13. Create user message in database
// Include threadId if provided (for SubAgent task execution in isolated Thread)
const userMessageRecord = await this.messageModel.create({
@@ -708,6 +759,7 @@ export class AiAgentService {
topicId,
});
log('execAgent: created assistant message %s', assistantMessageRecord.id);
+ assistantMessageRef.current = assistantMessageRecord.id;
// Create user message object for processing (include imageList for vision models)
const userMessage = { content: prompt, imageList, role: 'user' as const };
@@ -717,6 +769,8 @@ export class AiAgentService {
log('execAgent: prepared evalContext for executor');
+ await throwIfExecutionAborted('operation preparation');
+
// 15. Generate operation ID: agt_{timestamp}_{agentId}_{topicId}_{random}
const timestamp = Date.now();
const operationId = `op_${timestamp}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;
@@ -800,6 +854,7 @@ export class AiAgentService {
modelRuntimeConfig: { model, provider },
hooks,
operationId,
+ signal,
stepCallbacks,
stepWebhook,
stream,
@@ -833,6 +888,12 @@ export class AiAgentService {
userMessageId: userMessageRecord.id,
};
} catch (error) {
+ if (isAbortError(error)) {
+ await updateAbortedAssistantMessage(error.message);
+ log('execAgent: createOperation aborted for %s: %s', operationId, error.message);
+ throw error;
+ }
+
// Operation startup failed (e.g., QStash queue service unavailable)
// Update assistant message with error so user can see what went wrong
const errorMessage = error instanceof Error ? error.message : 'Unknown error starting agent';
@@ -1326,22 +1387,23 @@ export class AiAgentService {
throw new Error('Operation ID not found');
}
- // 2. Try to interrupt the operation
- // Note: AgentRuntimeService may not have interruptOperation method yet
- // We'll gracefully handle this case by only updating thread status
- try {
- // Check if the method exists before calling (using type assertion for future method)
- const service = this.agentRuntimeService as any;
- if (typeof service.interruptOperation === 'function') {
- await service.interruptOperation({
- operationId: resolvedOperationId,
- });
- } else {
- log('interruptTask: interruptOperation method not available, only updating thread status');
- }
- } catch (error: any) {
- log('interruptTask: Failed to interrupt operation: %O', error);
- // Continue to update Thread status even if operation interrupt fails
+ // 2. Interrupt the runtime operation first. Only mark the thread cancelled
+ // after the runtime acknowledges the interrupt to avoid unlocking a live task.
+ const interrupted = await this.agentRuntimeService.interruptOperation(resolvedOperationId);
+ log(
+ 'interruptTask: interruptOperation=%s for operationId=%s',
+ interrupted,
+ resolvedOperationId,
+ );
+
+ if (!interrupted) {
+ const alreadyCancelled = thread?.status === ThreadStatus.Cancel;
+
+ return {
+ operationId: resolvedOperationId,
+ success: alreadyCancelled,
+ threadId: thread?.id,
+ };
}
// 3. Update Thread status to cancel
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.ts
index 3450fa5b45e..de2c9a191bb 100644
--- a/src/server/services/bot/AgentBridgeService.ts
+++ b/src/server/services/bot/AgentBridgeService.ts
@@ -1,4 +1,4 @@
-import type { ChatTopicBotContext } from '@lobechat/types';
+import type { ChatTopicBotContext, ExecAgentResult } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import type { Message, SentMessage, Thread } from 'chat';
import { emoji } from 'chat';
@@ -9,6 +9,7 @@ import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import type { LobeChatDatabase } from '@/database/type';
import { appEnv } from '@/envs/app';
+import { createAbortError, isAbortError } from '@/server/services/agentRuntime/abort';
import { AiAgentService } from '@/server/services/aiAgent';
import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
import { SystemAgentService } from '@/server/services/systemAgent';
@@ -22,6 +23,7 @@ import {
renderFinalReply,
renderStart,
renderStepProgress,
+ renderStopped,
splitMessage,
} from './replyTemplate';
@@ -110,6 +112,90 @@ export class AgentBridgeService {
*/
private static activeThreads = new Set<string>();
+ /**
+ * Maps platform thread ID β†’ operationId for active executions.
+ * Used by /stop to interrupt a running agent via AiAgentService.interruptTask.
+ */
+ private static activeOperations = new Map<string, string>();
+
+ /**
+ * Abort controllers for startup work before execAgent returns an operationId.
+ * Allows /stop to cancel topic/tool/message preparation in the current process.
+ */
+ private static startupControllers = new Map<string, AbortController>();
+
+ /**
+ * Threads where the user requested /stop before we had an operationId.
+ * Once the operationId becomes available we immediately interrupt it.
+ */
+ private static pendingStopThreads = new Set<string>();
+
+ /**
+ * Check if a thread currently has an active agent execution.
+ */
+ static isThreadActive(threadId: string): boolean {
+ return AgentBridgeService.activeThreads.has(threadId);
+ }
+
+ /**
+ * Get the operationId for an active execution on the given thread.
+ */
+ static getActiveOperationId(threadId: string): string | undefined {
+ return AgentBridgeService.activeOperations.get(threadId);
+ }
+
+ /**
+ * Remove a thread from the active set, e.g. when /stop cancels execution.
+ */
+ static clearActiveThread(threadId: string): void {
+ AgentBridgeService.activeThreads.delete(threadId);
+ AgentBridgeService.activeOperations.delete(threadId);
+ AgentBridgeService.pendingStopThreads.delete(threadId);
+ AgentBridgeService.startupControllers.delete(threadId);
+ }
+
+ /**
+ * Mark a thread as waiting for interruption once its operationId is known.
+ */
+ static requestStop(threadId: string): void {
+ AgentBridgeService.pendingStopThreads.add(threadId);
+ const controller = AgentBridgeService.startupControllers.get(threadId);
+ if (controller && !controller.signal.aborted) {
+ controller.abort(createAbortError('Execution stopped before startup.'));
+ }
+ }
+
+ /**
+ * Consume a pending stop request for a thread.
+ */
+ static consumeStopRequest(threadId: string): boolean {
+ const hasPendingStop = AgentBridgeService.pendingStopThreads.has(threadId);
+ if (hasPendingStop) {
+ AgentBridgeService.pendingStopThreads.delete(threadId);
+ }
+ return hasPendingStop;
+ }
+
+ /**
+ * Run startup work under a per-thread AbortSignal so /stop can cancel it
+ * before an operationId exists.
+ */
+ private static async runWithStartupSignal<T>(
+ threadId: string,
+ task: (signal: AbortSignal) => Promise<T>,
+ ): Promise<T> {
+ const controller = new AbortController();
+ AgentBridgeService.startupControllers.set(threadId, controller);
+
+ try {
+ return await task(controller.signal);
+ } finally {
+ if (AgentBridgeService.startupControllers.get(threadId) === controller) {
+ AgentBridgeService.startupControllers.delete(threadId);
+ }
+ }
+ }
+
/**
* Debounce buffer for incoming messages per thread.
* Users often send multiple short messages in quick succession (e.g. "hello" + "how are you").
@@ -201,6 +287,42 @@ export class AgentBridgeService {
this.userId = userId;
}
+ private async interruptTrackedOperation(threadId: string, operationId: string): Promise<void> {
+ const aiAgentService = new AiAgentService(this.db, this.userId);
+ const result = await aiAgentService.interruptTask({ operationId });
+ if (!result.success) {
+ throw new Error(`Failed to interrupt operation ${operationId}`);
+ }
+ AgentBridgeService.clearActiveThread(threadId);
+ log('interruptTrackedOperation: thread=%s, operationId=%s', threadId, operationId);
+ }
+
+ private async finishStartupFailure(params: {
+ error?: unknown;
+ progressMessage?: SentMessage;
+ stopped?: boolean;
+ thread: Thread<ThreadState>;
+ userMessage: Message;
+ }): Promise<void> {
+ const { error, progressMessage, stopped, thread, userMessage } = params;
+ const errorMessage =
+ error instanceof Error ? error.message : error ? String(error) : 'Agent execution failed';
+
+ AgentBridgeService.clearActiveThread(thread.id);
+
+ if (progressMessage) {
+ try {
+ await progressMessage.edit(
+ stopped ? renderStopped(errorMessage) : renderError(errorMessage),
+ );
+ } catch (editError) {
+ log('finishStartupFailure: failed to edit progress message: %O', editError);
+ }
+ }
+
+ await this.removeReceivedReaction(thread, userMessage);
+ }
+
/**
* Handle a new @mention β€” start a fresh conversation.
*/
@@ -295,10 +417,12 @@ export class AgentBridgeService {
const msg = error instanceof Error ? error.message : String(error);
await thread.post(`**Agent Execution Failed**\n\`\`\`\n${msg}\n\`\`\``);
} finally {
- AgentBridgeService.activeThreads.delete(thread.id);
clearInterval(typingInterval);
- // In queue mode, reaction is removed by the bot-callback webhook on completion
+ // In queue mode, the agent is still running on the job queue after
+ // executeWithWebhooks returns. Keep the thread marked active so /stop
+ // can find and interrupt it. The completion callback clears it instead.
if (!queueMode) {
+ AgentBridgeService.activeThreads.delete(thread.id);
await this.removeReceivedReaction(thread, message, client);
}
}
@@ -398,10 +522,9 @@ export class AgentBridgeService {
log('handleSubscribedMessage error: %O', error);
await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${errMsg}\n\`\`\``);
} finally {
- AgentBridgeService.activeThreads.delete(thread.id);
clearInterval(typingInterval);
- // In queue mode, reaction is removed by the bot-callback webhook on completion
if (!queueMode) {
+ AgentBridgeService.activeThreads.delete(thread.id);
await this.removeReceivedReaction(thread, message, opts.client);
}
}
@@ -455,10 +578,10 @@ export class AgentBridgeService {
// The ack can't be edited into the final reply, so it would stay as a stale extra message.
const canEdit = platformRegistry.getPlatform(client?.id ?? '')?.supportsMessageEdit !== false;
+ let progressMessage: SentMessage | undefined;
let progressMessageId: string | undefined;
if (canEdit) {
// Post initial progress message to get the message ID
- let progressMessage: SentMessage | undefined;
try {
progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
} catch (error) {
@@ -505,23 +628,48 @@ export class AgentBridgeService {
files?.length ?? 0,
);
- const result = await aiAgentService.execAgent({
- agentId,
- appContext: topicId ? { topicId } : undefined,
- autoStart: true,
- botContext,
- completionWebhook: { body: webhookBody, url: callbackUrl },
- discordContext: channelContext
- ? { channel: channelContext.channel, guild: channelContext.guild }
- : undefined,
- files,
- prompt,
- stepWebhook: { body: webhookBody, url: callbackUrl },
- title: '',
- trigger,
- userInterventionConfig: { approvalMode: 'headless' },
- webhookDelivery: 'qstash',
- });
+ let result: ExecAgentResult;
+ try {
+ result = await AgentBridgeService.runWithStartupSignal(thread.id, (signal) =>
+ aiAgentService.execAgent({
+ agentId,
+ appContext: topicId ? { topicId } : undefined,
+ autoStart: true,
+ botContext,
+ completionWebhook: { body: webhookBody, url: callbackUrl },
+ discordContext: channelContext
+ ? { channel: channelContext.channel, guild: channelContext.guild }
+ : undefined,
+ files,
+ prompt,
+ signal,
+ stepWebhook: { body: webhookBody, url: callbackUrl },
+ title: '',
+ trigger,
+ userInterventionConfig: { approvalMode: 'headless' },
+ webhookDelivery: 'qstash',
+ }),
+ );
+ } catch (error) {
+ await this.finishStartupFailure({
+ error,
+ progressMessage,
+ stopped: isAbortError(error),
+ thread,
+ userMessage,
+ });
+ return { reply: '', topicId: topicId ?? '' };
+ }
+
+ if (!result.success) {
+ await this.finishStartupFailure({
+ error: result.error,
+ progressMessage,
+ thread,
+ userMessage,
+ });
+ return { reply: '', topicId: result.topicId };
+ }
log(
'executeWithWebhooks: operationId=%s, topicId=%s (webhook mode, returning immediately)',
@@ -529,6 +677,24 @@ export class AgentBridgeService {
result.topicId,
);
+ // Track operationId so /stop can interrupt this execution
+ if (result.operationId) {
+ AgentBridgeService.activeOperations.set(thread.id, result.operationId);
+
+ if (AgentBridgeService.consumeStopRequest(thread.id)) {
+ try {
+ await this.interruptTrackedOperation(thread.id, result.operationId);
+ } catch (error) {
+ log(
+ 'executeWithWebhooks: deferred stop failed for thread=%s, operationId=%s: %O',
+ thread.id,
+ result.operationId,
+ error,
+ );
+ }
+ }
+ }
+
// Return immediately β€” progress/completion handled by webhooks
return { reply: '', topicId: result.topicId };
}
@@ -583,8 +749,8 @@ export class AgentBridgeService {
reject(new Error(`Agent execution timed out`));
}, EXECUTION_TIMEOUT);
- let assistantMessageId: string;
- let resolvedTopicId: string;
+ let assistantMessageId = '';
+ let resolvedTopicId = topicId ?? '';
const getElapsedMs = () => (operationStartTime > 0 ? Date.now() - operationStartTime : 0);
@@ -598,8 +764,8 @@ export class AgentBridgeService {
files?.length ?? 0,
);
- aiAgentService
- .execAgent({
+ AgentBridgeService.runWithStartupSignal(thread.id, (signal) =>
+ aiAgentService.execAgent({
agentId,
appContext: topicId ? { topicId } : undefined,
autoStart: true,
@@ -609,6 +775,7 @@ export class AgentBridgeService {
: undefined,
files,
prompt,
+ signal,
title: '',
stepCallbacks: {
onAfterStep: async (stepData) => {
@@ -663,6 +830,18 @@ export class AgentBridgeService {
return;
}
+ if (reason === 'interrupted') {
+ if (progressMessage) {
+ try {
+ await progressMessage.edit(renderStopped());
+ } catch {
+ // ignore edit failure
+ }
+ }
+ resolve({ reply: '', topicId: resolvedTopicId });
+ return;
+ }
+
try {
// Extract reply from finalState.messages (accumulated across all steps)
const lastAssistantContent = finalState.messages
@@ -745,12 +924,48 @@ export class AgentBridgeService {
},
trigger,
userInterventionConfig: { approvalMode: 'headless' },
- })
- .then((result) => {
+ }),
+ )
+ .then(async (result) => {
assistantMessageId = result.assistantMessageId;
resolvedTopicId = result.topicId;
operationStartTime = new Date(result.createdAt).getTime();
+ if (!result.success) {
+ clearTimeout(timeout);
+
+ if (progressMessage) {
+ try {
+ await progressMessage.edit(
+ renderError(result.error || 'Agent operation failed to start'),
+ );
+ } catch (error) {
+ log('executeWithInMemoryCallbacks: failed to edit startup error: %O', error);
+ }
+ }
+
+ resolve({ reply: '', topicId: result.topicId });
+ return;
+ }
+
+ // Track operationId so /stop can interrupt this execution
+ if (result.operationId) {
+ AgentBridgeService.activeOperations.set(thread.id, result.operationId);
+
+ if (AgentBridgeService.consumeStopRequest(thread.id)) {
+ try {
+ await this.interruptTrackedOperation(thread.id, result.operationId);
+ } catch (error) {
+ log(
+ 'executeWithInMemoryCallbacks: deferred stop failed for thread=%s, operationId=%s: %O',
+ thread.id,
+ result.operationId,
+ error,
+ );
+ }
+ }
+ }
+
log(
'executeWithInMemoryCallbacks: operationId=%s, assistantMessageId=%s, topicId=%s',
result.operationId,
@@ -758,9 +973,31 @@ export class AgentBridgeService {
result.topicId,
);
})
- .catch((error) => {
+ .catch(async (error) => {
clearTimeout(timeout);
- reject(error);
+
+ if (isAbortError(error)) {
+ if (progressMessage) {
+ try {
+ await progressMessage.edit(renderStopped(error.message));
+ } catch (editError) {
+ log('executeWithInMemoryCallbacks: failed to edit stopped message: %O', editError);
+ }
+ }
+
+ resolve({ reply: '', topicId: topicId ?? '' });
+ return;
+ }
+
+ if (progressMessage) {
+ try {
+ await progressMessage.edit(renderError(extractErrorMessage(error)));
+ } catch (editError) {
+ log('executeWithInMemoryCallbacks: failed to edit startup error: %O', editError);
+ }
+ }
+
+ resolve({ reply: '', topicId: topicId ?? '' });
});
});
}
diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.ts
index b0110a9d8ed..d4d31175ab7 100644
--- a/src/server/services/bot/BotCallbackService.ts
+++ b/src/server/services/bot/BotCallbackService.ts
@@ -7,9 +7,16 @@ import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis'
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { SystemAgentService } from '@/server/services/systemAgent';
+import { AgentBridgeService } from './AgentBridgeService';
import type { BotProviderConfig, PlatformClient, PlatformMessenger, UsageStats } from './platforms';
import { platformRegistry } from './platforms';
-import { renderError, renderFinalReply, renderStepProgress, splitMessage } from './replyTemplate';
+import {
+ renderError,
+ renderFinalReply,
+ renderStepProgress,
+ renderStopped,
+ splitMessage,
+} from './replyTemplate';
const log = debug('lobe-server:bot:callback');
@@ -89,6 +96,10 @@ export class BotCallbackService {
canEdit,
);
await this.removeEyesReaction(body, client, platformThreadId);
+ // Clear the active thread tracker so the thread can accept new messages.
+ // In queue mode, the bridge handler's finally block skips this cleanup
+ // to keep the thread marked active while the agent runs on the job queue.
+ AgentBridgeService.clearActiveThread(platformThreadId);
this.summarizeTopicTitle(body, messenger);
}
}
@@ -211,6 +222,16 @@ export class BotCallbackService {
return;
}
+ if (reason === 'interrupted') {
+ const stoppedText = renderStopped(errorMessage || 'Execution stopped.');
+ try {
+ await messenger.createMessage(stoppedText);
+ } catch (error) {
+ log('handleCompletion: failed to send interrupted message: %O', error);
+ }
+ return;
+ }
+
if (!lastAssistantContent) {
log('handleCompletion: no lastAssistantContent, skipping');
return;
@@ -269,7 +290,16 @@ export class BotCallbackService {
private summarizeTopicTitle(body: BotCallbackBody, messenger: PlatformMessenger): void {
const { reason, topicId, userId, userPrompt, lastAssistantContent } = body;
- if (reason === 'error' || !topicId || !userId || !userPrompt || !lastAssistantContent) return;
+ if (
+ reason === 'error' ||
+ reason === 'interrupted' ||
+ !topicId ||
+ !userId ||
+ !userPrompt ||
+ !lastAssistantContent
+ ) {
+ return;
+ }
const topicModel = new TopicModel(this.db, userId);
topicModel
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index d0f1b4d0d07..351d8771b7a 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -8,6 +8,7 @@ import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
import type { LobeChatDatabase } from '@/database/type';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { AiAgentService } from '@/server/services/aiAgent';
import { AgentBridgeService } from './AgentBridgeService';
import {
@@ -32,6 +33,24 @@ interface RegisteredBot {
client: PlatformClient;
}
+/** Context passed to every command handler β€” a minimal surface shared by both
+ * native slash-command events and text-based message events. */
+interface CommandContext {
+ /** Text after the command name (e.g. "/new foo" β†’ "foo"). */
+ args: string;
+ post: (text: string) => Promise<any>;
+ setState: (state: Record<string, any>, opts?: { replace?: boolean }) => Promise<any>;
+ threadId: string;
+}
+
+/** A single bot command definition.
+ * Add new entries to `buildCommands()` to register additional commands. */
+interface BotCommand {
+ description: string;
+ handler: (ctx: CommandContext) => Promise<void>;
+ name: string;
+}
+
/**
* Routes incoming webhook events to the correct Chat SDK Bot instance
* and triggers message processing via AgentBridgeService.
@@ -192,8 +211,10 @@ export class BotMessageRouter {
const client = entry.clientFactory.createClient(providerConfig, runtimeContext);
const adapters = client.createAdapter();
+ const commands = this.buildCommands(serverDB, { agentId, platform, userId });
+
const chatBot = this.createChatBot(adapters, `agent-${agentId}`);
- this.registerHandlers(chatBot, serverDB, client, {
+ this.registerHandlers(chatBot, serverDB, client, commands, {
agentId,
applicationId,
platform,
@@ -201,6 +222,15 @@ export class BotMessageRouter {
userId,
});
await chatBot.initialize();
+ client.applyChatPatches?.(chatBot);
+
+ // Register platform-specific bot commands (e.g., Telegram setMyCommands menu)
+ if (client.registerBotCommands) {
+ const commandList = commands.map((c) => ({ command: c.name, description: c.description }));
+ client.registerBotCommands(commandList).catch((error) => {
+ log('registerBotCommands failed for %s: %O', key, error);
+ });
+ }
const registered: RegisteredBot = {
agentInfo: { agentId, userId },
@@ -276,6 +306,7 @@ export class BotMessageRouter {
bot: Chat<any>,
serverDB: LobeChatDatabase,
client: PlatformClient,
+ commands: BotCommand[],
info: ResolvedAgentInfo & {
applicationId: string;
platform: string;
@@ -287,7 +318,29 @@ export class BotMessageRouter {
const charLimit = (info.settings?.charLimit as number) || undefined;
const debounceMs = (info.settings?.debounceMs as number) || undefined;
+ /** Try dispatching a text command. Returns true if handled. */
+ const tryDispatch = async (
+ thread: {
+ id: string;
+ post: (t: string) => Promise<any>;
+ setState: (s: Record<string, any>, o?: { replace?: boolean }) => Promise<any>;
+ },
+ text: string | undefined,
+ ): Promise<boolean> => {
+ const result = BotMessageRouter.dispatchTextCommand(text, commands);
+ if (!result) return false;
+ await result.command.handler({
+ args: result.args,
+ post: (t) => thread.post(t),
+ setState: (s, o) => thread.setState(s, o),
+ threadId: thread.id,
+ });
+ return true;
+ };
+
bot.onNewMention(async (thread, message) => {
+ if (await tryDispatch(thread, message.text)) return;
+
log(
'onNewMention: agent=%s, platform=%s, author=%s, thread=%s',
agentId,
@@ -306,6 +359,7 @@ export class BotMessageRouter {
bot.onSubscribedMessage(async (thread, message) => {
if (message.author.isBot === true) return;
+ if (await tryDispatch(thread, message.text)) return;
log(
'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s',
@@ -324,12 +378,18 @@ export class BotMessageRouter {
});
});
+ // Register slash command handlers (native + text-based)
+ this.registerCommands(bot, commands);
+
// Register onNewMessage handler based on platform config
const dmEnabled = info.settings?.dm?.enabled ?? false;
if (dmEnabled) {
bot.onNewMessage(/./, async (thread, message) => {
if (message.author.isBot === true) return;
+ // Skip text-based slash commands β€” already handled by registerCommands
+ if (BotMessageRouter.dispatchTextCommand(message.text, commands)) return;
+
log(
'onNewMessage (%s catch-all): agent=%s, author=%s, thread=%s, text=%s',
platform,
@@ -349,6 +409,127 @@ export class BotMessageRouter {
});
}
}
+
+ // ------------------------------------------------------------------
+ // Command registry
+ // ------------------------------------------------------------------
+
+ /**
+ * Build the list of bot commands. Each entry defines a name, description,
+ * and handler. To add a new command, just append to this array.
+ *
+ * Handlers close over serverDB / userId / agentId / platform so they can
+ * access services without needing those passed through CommandContext.
+ */
+ private buildCommands(
+ serverDB: LobeChatDatabase,
+ info: { agentId: string; platform: string; userId: string },
+ ): BotCommand[] {
+ const { agentId, platform, userId } = info;
+
+ return [
+ {
+ description: 'Start a new conversation',
+ handler: async (ctx) => {
+ log('command /new: agent=%s, platform=%s', agentId, platform);
+ await ctx.setState({ topicId: undefined }, { replace: true });
+ await ctx.post('Conversation reset. Your next message will start a new topic.');
+ },
+ name: 'new',
+ },
+ {
+ description: 'Stop the current execution',
+ handler: async (ctx) => {
+ log('command /stop: agent=%s, platform=%s', agentId, platform);
+ const isActive = AgentBridgeService.isThreadActive(ctx.threadId);
+ if (!isActive) {
+ await ctx.post('No active execution to stop.');
+ return;
+ }
+ const operationId = AgentBridgeService.getActiveOperationId(ctx.threadId);
+ if (operationId) {
+ try {
+ const aiAgentService = new AiAgentService(serverDB, userId);
+ const result = await aiAgentService.interruptTask({ operationId });
+ if (!result.success) {
+ log('command /stop: runtime interrupt rejected for operationId=%s', operationId);
+ await ctx.post('Unable to stop the current execution.');
+ return;
+ }
+ AgentBridgeService.clearActiveThread(ctx.threadId);
+ log('command /stop: interrupted operationId=%s', operationId);
+ } catch (error) {
+ log('command /stop: interruptTask failed: %O', error);
+ await ctx.post('Unable to stop the current execution.');
+ return;
+ }
+ } else {
+ AgentBridgeService.requestStop(ctx.threadId);
+ log('command /stop: queued deferred stop for thread=%s', ctx.threadId);
+ }
+ await ctx.post('Stop requested.');
+ },
+ name: 'stop',
+ },
+ ];
+ }
+
+ /**
+ * Parse a text message for a registered command.
+ * Handles formats: "/cmd", "/cmd args", "/cmd@botname args" (Telegram).
+ * Returns the matched command and any trailing arguments, or null.
+ */
+ private static dispatchTextCommand(
+ text: string | undefined,
+ commands: BotCommand[],
+ ): { args: string; command: BotCommand } | null {
+ if (!text) return null;
+ const match = text.trim().match(/^\/(\w+)(?:@\w+)?(?:\s(.*))?$/s);
+ if (!match) return null;
+ const name = match[1].toLowerCase();
+ const command = commands.find((c) => c.name === name);
+ if (!command) return null;
+ return { args: match[2]?.trim() ?? '', command };
+ }
+
+ /**
+ * Register all commands on the bot via both native slash-command events
+ * (Slack, Discord) and text-based onNewMessage handlers (Telegram, Feishu, etc.).
+ *
+ * To add a new command, add an entry to `buildCommands()` β€” it will be
+ * automatically registered on all platforms.
+ */
+ private registerCommands(bot: Chat<any>, commands: BotCommand[]): void {
+ // --- Native slash commands (Slack, Discord) ---
+ for (const cmd of commands) {
+ bot.onSlashCommand(`/${cmd.name}`, async (event) => {
+ await cmd.handler({
+ args: event.text,
+ post: (text) => event.channel.post(text),
+ setState: (state, opts) => event.channel.setState(state, opts),
+ threadId: event.channel.id,
+ });
+ });
+ }
+
+ // --- Text-based slash commands (Telegram, Feishu, etc.) ---
+ // Platforms that don't support native onSlashCommand send /commands as
+ // regular text messages. This handler intercepts them in unsubscribed
+ // threads (e.g. first command in a group chat or DM).
+ const namePattern = commands.map((c) => c.name).join('|');
+ const regex = new RegExp(`^\\/(?:${namePattern})(?:\\s|$|@)`);
+ bot.onNewMessage(regex, async (thread, message) => {
+ if (message.author.isBot === true) return;
+ const result = BotMessageRouter.dispatchTextCommand(message.text, commands);
+ if (!result) return;
+ await result.command.handler({
+ args: result.args,
+ post: (text) => thread.post(text),
+ setState: (state, opts) => thread.setState(state, opts),
+ threadId: thread.id,
+ });
+ });
+ }
}
// ------------------------------------------------------------------
diff --git a/src/server/services/bot/__tests__/BotCallbackService.test.ts b/src/server/services/bot/__tests__/BotCallbackService.test.ts
index 22451b6c89b..f1dbf22eb38 100644
--- a/src/server/services/bot/__tests__/BotCallbackService.test.ts
+++ b/src/server/services/bot/__tests__/BotCallbackService.test.ts
@@ -68,6 +68,12 @@ vi.mock('@/server/modules/AgentRuntime/redis', () => ({
getAgentRuntimeRedisClient: vi.fn().mockReturnValue(null),
}));
+vi.mock('../AgentBridgeService', () => ({
+ AgentBridgeService: {
+ clearActiveThread: vi.fn(),
+ },
+}));
+
vi.mock('@/server/services/systemAgent', () => ({
SystemAgentService: vi.fn().mockImplementation(() => ({
generateTopicTitle: mockGenerateTopicTitle,
@@ -335,6 +341,33 @@ describe('BotCallbackService', () => {
);
});
+ it('should render stopped message when reason is interrupted', async () => {
+ const body = makeBody({
+ lastAssistantContent: 'Partial answer that should not be shown',
+ reason: 'interrupted',
+ type: 'completion',
+ });
+
+ await service.handleCallback(body);
+
+ expect(mockCreateMessage).toHaveBeenCalledWith('Execution stopped.');
+ expect(mockEditMessage).not.toHaveBeenCalled();
+ });
+
+ it('should render custom stopped message when interrupted has errorMessage', async () => {
+ const body = makeBody({
+ errorMessage: 'Execution stopped by user.',
+ lastAssistantContent: 'Partial answer that should not be shown',
+ reason: 'interrupted',
+ type: 'completion',
+ });
+
+ await service.handleCallback(body);
+
+ expect(mockCreateMessage).toHaveBeenCalledWith('Execution stopped by user.');
+ expect(mockEditMessage).not.toHaveBeenCalled();
+ });
+
it('should skip when no lastAssistantContent on successful completion', async () => {
const body = makeBody({
reason: 'completed',
@@ -377,6 +410,17 @@ describe('BotCallbackService', () => {
await expect(service.handleCallback(body)).resolves.toBeUndefined();
});
+
+ it('should not throw when sending interrupted message fails', async () => {
+ mockCreateMessage.mockRejectedValueOnce(new Error('Send failed'));
+
+ const body = makeBody({
+ reason: 'interrupted',
+ type: 'completion',
+ });
+
+ await expect(service.handleCallback(body)).resolves.toBeUndefined();
+ });
});
// ==================== Message splitting ====================
@@ -565,6 +609,24 @@ describe('BotCallbackService', () => {
expect(mockFindById).not.toHaveBeenCalled();
});
+ it('should skip summarization when reason is interrupted', async () => {
+ const body = makeBody({
+ lastAssistantContent: 'partial',
+ reason: 'interrupted',
+ topicId: 'topic-1',
+ type: 'completion',
+ userId: 'user-1',
+ userPrompt: 'test',
+ });
+
+ await service.handleCallback(body);
+
+ await new Promise((r) => setTimeout(r, 50));
+ expect(mockFindById).not.toHaveBeenCalled();
+ expect(mockGenerateTopicTitle).not.toHaveBeenCalled();
+ expect(mockTopicUpdate).not.toHaveBeenCalled();
+ });
+
it('should skip summarization when topicId is missing', async () => {
const body = makeBody({
lastAssistantContent: 'Done.',
diff --git a/src/server/services/bot/__tests__/BotMessageRouter.test.ts b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
index 0763ee74a6a..5d91c35970a 100644
--- a/src/server/services/bot/__tests__/BotMessageRouter.test.ts
+++ b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
@@ -37,6 +37,7 @@ const mockInitialize = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
const mockOnNewMention = vi.hoisted(() => vi.fn());
const mockOnSubscribedMessage = vi.hoisted(() => vi.fn());
const mockOnNewMessage = vi.hoisted(() => vi.fn());
+const mockOnSlashCommand = vi.hoisted(() => vi.fn());
vi.mock('chat', () => ({
BaseFormatConverter: class {},
@@ -44,12 +45,19 @@ vi.mock('chat', () => ({
initialize: mockInitialize,
onNewMention: mockOnNewMention,
onNewMessage: mockOnNewMessage,
+ onSlashCommand: mockOnSlashCommand,
onSubscribedMessage: mockOnSubscribedMessage,
webhooks: {},
})),
ConsoleLogger: vi.fn(),
}));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(() => ({
+ interruptTask: vi.fn().mockResolvedValue({ success: true }),
+ })),
+}));
+
vi.mock('../AgentBridgeService', () => ({
AgentBridgeService: vi.fn().mockImplementation(() => ({
handleMention: vi.fn().mockResolvedValue(undefined),
@@ -242,10 +250,11 @@ describe('BotMessageRouter', () => {
const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
await handler(req);
- expect(mockOnNewMessage).toHaveBeenCalled();
+ // Called twice: once for text-based slash commands, once for DM catch-all
+ expect(mockOnNewMessage).toHaveBeenCalledTimes(2);
});
- it('should NOT register onNewMessage when dm is not enabled', async () => {
+ it('should NOT register DM onNewMessage when dm is not enabled', async () => {
mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'app-123' })]);
const router = new BotMessageRouter();
@@ -254,7 +263,8 @@ describe('BotMessageRouter', () => {
const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
await handler(req);
- expect(mockOnNewMessage).not.toHaveBeenCalled();
+ // Called once for text-based slash commands only, no DM catch-all
+ expect(mockOnNewMessage).toHaveBeenCalledTimes(1);
});
});
});
diff --git a/src/server/services/bot/platforms/discord/api.ts b/src/server/services/bot/platforms/discord/api.ts
index 31c02f63cd2..d8ff0f12874 100644
--- a/src/server/services/bot/platforms/discord/api.ts
+++ b/src/server/services/bot/platforms/discord/api.ts
@@ -1,6 +1,10 @@
import { REST } from '@discordjs/rest';
import debug from 'debug';
-import { type RESTPostAPIChannelMessageResult, Routes } from 'discord-api-types/v10';
+import {
+ ApplicationCommandType,
+ type RESTPostAPIChannelMessageResult,
+ Routes,
+} from 'discord-api-types/v10';
const log = debug('bot-platform:discord:client');
@@ -42,4 +46,18 @@ export class DiscordApi {
return { id: data.id };
}
+
+ async registerCommands(
+ applicationId: string,
+ commands: Array<{ command: string; description: string }>,
+ ): Promise<void> {
+ log('registerCommands: appId=%s, %d commands', applicationId, commands.length);
+ await this.rest.put(Routes.applicationCommands(applicationId), {
+ body: commands.map((c) => ({
+ description: c.description,
+ name: c.command,
+ type: ApplicationCommandType.ChatInput,
+ })),
+ });
+ }
}
diff --git a/src/server/services/bot/platforms/discord/client.ts b/src/server/services/bot/platforms/discord/client.ts
index a4759f49e37..38e7564fac3 100644
--- a/src/server/services/bot/platforms/discord/client.ts
+++ b/src/server/services/bot/platforms/discord/client.ts
@@ -1,5 +1,6 @@
import type { DiscordAdapter } from '@chat-adapter/discord';
import { createDiscordAdapter } from '@chat-adapter/discord';
+import type { Chat as ChatBot } from 'chat';
import debug from 'debug';
import {
@@ -13,6 +14,7 @@ import {
} from '../types';
import { formatUsageStats } from '../utils';
import { DiscordApi } from './api';
+import { patchDiscordForwardedInteractions } from './patch';
const log = debug('bot-platform:discord:bot');
@@ -122,6 +124,10 @@ class DiscordGatewayClient implements PlatformClient {
// --- Runtime Operations ---
+ applyChatPatches(chatBot: ChatBot<any>): void {
+ patchDiscordForwardedInteractions(chatBot);
+ }
+
createAdapter(): Record<string, any> {
return {
discord: createDiscordAdapter({
@@ -177,6 +183,13 @@ class DiscordGatewayClient implements PlatformClient {
sanitizeUserInput(text: string): string {
return text.replaceAll(new RegExp(`<@!?${this.applicationId}>\\s*`, 'g'), '').trim();
}
+
+ async registerBotCommands(
+ commands: Array<{ command: string; description: string }>,
+ ): Promise<void> {
+ await this.discord.registerCommands(this.applicationId, commands);
+ log('DiscordBot appId=%s registered %d commands', this.applicationId, commands.length);
+ }
}
export class DiscordClientFactory extends ClientFactory {
diff --git a/src/server/services/bot/platforms/discord/patch/forwardedInteractions.test.ts b/src/server/services/bot/platforms/discord/patch/forwardedInteractions.test.ts
new file mode 100644
index 00000000000..d3092f0e004
--- /dev/null
+++ b/src/server/services/bot/platforms/discord/patch/forwardedInteractions.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { patchDiscordForwardedInteractions } from './forwardedInteractions';
+
+describe('patchDiscordForwardedInteractions', () => {
+ it('should ACK and dispatch forwarded slash commands', async () => {
+ const originalHandleForwardedGatewayEvent = vi.fn();
+ const discordInteractionFetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
+ const handleApplicationCommandInteraction = vi.fn();
+ const handleComponentInteraction = vi.fn();
+
+ const adapter = {
+ discordInteractionFetch,
+ handleApplicationCommandInteraction,
+ handleComponentInteraction,
+ handleForwardedGatewayEvent: originalHandleForwardedGatewayEvent,
+ };
+
+ const chatBot = {
+ adapters: new Map([['discord', adapter]]),
+ } as any;
+
+ patchDiscordForwardedInteractions(chatBot);
+
+ const response = await adapter.handleForwardedGatewayEvent(
+ {
+ data: { id: 'interaction-1', token: 'token-1', type: 2 },
+ type: 'GATEWAY_INTERACTION_CREATE',
+ },
+ { foo: 'bar' },
+ );
+
+ expect(discordInteractionFetch).toHaveBeenCalledWith(
+ '/interactions/interaction-1/token-1/callback',
+ 'POST',
+ { type: 5 },
+ );
+ expect(handleApplicationCommandInteraction).toHaveBeenCalledWith(
+ { id: 'interaction-1', token: 'token-1', type: 2 },
+ { foo: 'bar' },
+ );
+ expect(handleComponentInteraction).not.toHaveBeenCalled();
+ expect(originalHandleForwardedGatewayEvent).not.toHaveBeenCalled();
+ expect(response.status).toBe(200);
+ });
+
+ it('should ACK and dispatch forwarded component interactions', async () => {
+ const originalHandleForwardedGatewayEvent = vi.fn();
+ const discordInteractionFetch = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
+ const handleApplicationCommandInteraction = vi.fn();
+ const handleComponentInteraction = vi.fn();
+
+ const adapter = {
+ discordInteractionFetch,
+ handleApplicationCommandInteraction,
+ handleComponentInteraction,
+ handleForwardedGatewayEvent: originalHandleForwardedGatewayEvent,
+ };
+
+ const chatBot = {
+ adapters: new Map([['discord', adapter]]),
+ } as any;
+
+ patchDiscordForwardedInteractions(chatBot);
+
+ await adapter.handleForwardedGatewayEvent(
+ {
+ data: { id: 'interaction-2', token: 'token-2', type: 3 },
+ type: 'GATEWAY_INTERACTION_CREATE',
+ },
+ { foo: 'bar' },
+ );
+
+ expect(discordInteractionFetch).toHaveBeenCalledWith(
+ '/interactions/interaction-2/token-2/callback',
+ 'POST',
+ { type: 6 },
+ );
+ expect(handleComponentInteraction).toHaveBeenCalledWith(
+ { id: 'interaction-2', token: 'token-2', type: 3 },
+ { foo: 'bar' },
+ );
+ expect(handleApplicationCommandInteraction).not.toHaveBeenCalled();
+ expect(originalHandleForwardedGatewayEvent).not.toHaveBeenCalled();
+ });
+
+ it('should fall back to the original forwarded handler for non-interaction events', async () => {
+ const originalResponse = new Response(JSON.stringify({ ok: true }), { status: 200 });
+ const originalHandleForwardedGatewayEvent = vi.fn().mockResolvedValue(originalResponse);
+ const discordInteractionFetch = vi.fn();
+ const handleApplicationCommandInteraction = vi.fn();
+ const handleComponentInteraction = vi.fn();
+
+ const adapter = {
+ discordInteractionFetch,
+ handleApplicationCommandInteraction,
+ handleComponentInteraction,
+ handleForwardedGatewayEvent: originalHandleForwardedGatewayEvent,
+ };
+
+ const chatBot = {
+ adapters: new Map([['discord', adapter]]),
+ } as any;
+
+ patchDiscordForwardedInteractions(chatBot);
+
+ const response = await adapter.handleForwardedGatewayEvent(
+ { data: { id: 'msg-1' }, type: 'GATEWAY_MESSAGE_CREATE' },
+ { foo: 'bar' },
+ );
+
+ expect(originalHandleForwardedGatewayEvent).toHaveBeenCalledWith(
+ { data: { id: 'msg-1' }, type: 'GATEWAY_MESSAGE_CREATE' },
+ { foo: 'bar' },
+ );
+ expect(discordInteractionFetch).not.toHaveBeenCalled();
+ expect(handleApplicationCommandInteraction).not.toHaveBeenCalled();
+ expect(handleComponentInteraction).not.toHaveBeenCalled();
+ expect(response).toBe(originalResponse);
+ });
+});
diff --git a/src/server/services/bot/platforms/discord/patch/forwardedInteractions.ts b/src/server/services/bot/platforms/discord/patch/forwardedInteractions.ts
new file mode 100644
index 00000000000..1a10e7b2b10
--- /dev/null
+++ b/src/server/services/bot/platforms/discord/patch/forwardedInteractions.ts
@@ -0,0 +1,115 @@
+import type { Chat } from 'chat';
+
+const FORWARDED_INTERACTION_EVENT = 'GATEWAY_INTERACTION_CREATE';
+const APPLICATION_COMMAND_INTERACTION = 2;
+const MESSAGE_COMPONENT_INTERACTION = 3;
+const DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5;
+const DEFERRED_UPDATE_MESSAGE = 6;
+const PATCHED_FLAG = Symbol.for('lobe.discord.forwarded-interactions.patched');
+
+interface ForwardedGatewayEvent {
+ data?: Record<string, unknown>;
+ type?: string;
+}
+
+interface ForwardedInteraction {
+ id: string;
+ token: string;
+ type: number;
+}
+
+interface ForwardedInteractionAdapter {
+ discordInteractionFetch: (
+ path: string,
+ method: string,
+ body: Record<string, unknown>,
+ ) => Promise<Response>;
+ handleApplicationCommandInteraction: (
+ interaction: ForwardedInteraction,
+ options?: unknown,
+ ) => void;
+ handleComponentInteraction: (interaction: ForwardedInteraction, options?: unknown) => void;
+ handleForwardedGatewayEvent: (
+ event: ForwardedGatewayEvent,
+ options?: unknown,
+ ) => Promise<Response>;
+ [PATCHED_FLAG]?: boolean;
+}
+
+const okResponse = () =>
+ new Response(JSON.stringify({ ok: true }), {
+ headers: { 'Content-Type': 'application/json' },
+ status: 200,
+ });
+
+const isForwardedInteractionAdapter = (
+ adapter: unknown,
+): adapter is ForwardedInteractionAdapter => {
+ if (!adapter || typeof adapter !== 'object') return false;
+
+ return (
+ typeof (adapter as ForwardedInteractionAdapter).discordInteractionFetch === 'function' &&
+ typeof (adapter as ForwardedInteractionAdapter).handleApplicationCommandInteraction ===
+ 'function' &&
+ typeof (adapter as ForwardedInteractionAdapter).handleComponentInteraction === 'function' &&
+ typeof (adapter as ForwardedInteractionAdapter).handleForwardedGatewayEvent === 'function'
+ );
+};
+
+const getDeferredResponseType = (interactionType: number) => {
+ switch (interactionType) {
+ case APPLICATION_COMMAND_INTERACTION: {
+ return DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE;
+ }
+ case MESSAGE_COMPONENT_INTERACTION: {
+ return DEFERRED_UPDATE_MESSAGE;
+ }
+ default: {
+ return null;
+ }
+ }
+};
+
+export const patchDiscordForwardedInteractions = (chatBot: Chat<any>) => {
+ const adapter = (chatBot as any).adapters?.get?.('discord');
+
+ if (!isForwardedInteractionAdapter(adapter) || adapter[PATCHED_FLAG]) return;
+
+ const originalHandleForwardedGatewayEvent = adapter.handleForwardedGatewayEvent.bind(adapter);
+
+ adapter.handleForwardedGatewayEvent = async (event, options) => {
+ if (event?.type !== FORWARDED_INTERACTION_EVENT) {
+ return originalHandleForwardedGatewayEvent(event, options);
+ }
+
+ const interaction = event.data as Partial<ForwardedInteraction> | undefined;
+
+ if (!interaction?.id || !interaction.token || typeof interaction.type !== 'number') {
+ return originalHandleForwardedGatewayEvent(event, options);
+ }
+
+ const responseType = getDeferredResponseType(interaction.type);
+
+ if (!responseType) {
+ return originalHandleForwardedGatewayEvent(event, options);
+ }
+
+ // Gateway-forwarded interactions bypass Discord's HTTP webhook response path,
+ // so we must send the deferred callback manually before dispatching handlers.
+ await adapter.discordInteractionFetch(
+ `/interactions/${interaction.id}/${interaction.token}/callback`,
+ 'POST',
+ { type: responseType },
+ );
+
+ if (interaction.type === APPLICATION_COMMAND_INTERACTION) {
+ adapter.handleApplicationCommandInteraction(interaction as ForwardedInteraction, options);
+ } else {
+ adapter.handleComponentInteraction(interaction as ForwardedInteraction, options);
+ }
+
+ return okResponse();
+ };
+
+ adapter[PATCHED_FLAG] = true;
+};
diff --git a/src/server/services/bot/platforms/discord/patch/index.ts b/src/server/services/bot/platforms/discord/patch/index.ts
new file mode 100644
index 00000000000..8f38a40109e
--- /dev/null
+++ b/src/server/services/bot/platforms/discord/patch/index.ts
@@ -0,0 +1 @@
+export * from './forwardedInteractions';
diff --git a/src/server/services/bot/platforms/telegram/api.ts b/src/server/services/bot/platforms/telegram/api.ts
index a33adfdbfc7..74a2a3956b6 100644
--- a/src/server/services/bot/platforms/telegram/api.ts
+++ b/src/server/services/bot/platforms/telegram/api.ts
@@ -71,6 +71,11 @@ export class TelegramApi {
});
}
+ async setMyCommands(commands: Array<{ command: string; description: string }>): Promise<void> {
+ log('setMyCommands: %d commands', commands.length);
+ await this.call('setMyCommands', { commands });
+ }
+
// ------------------------------------------------------------------
private truncateText(text: string): string {
diff --git a/src/server/services/bot/platforms/telegram/client.ts b/src/server/services/bot/platforms/telegram/client.ts
index fe62857a161..848d7d6a01a 100644
--- a/src/server/services/bot/platforms/telegram/client.ts
+++ b/src/server/services/bot/platforms/telegram/client.ts
@@ -101,6 +101,14 @@ class TelegramWebhookClient implements PlatformClient {
return extractChatId(platformThreadId);
}
+ async registerBotCommands(
+ commands: Array<{ command: string; description: string }>,
+ ): Promise<void> {
+ const telegram = new TelegramApi(this.config.credentials.botToken);
+ await telegram.setMyCommands(commands);
+ log('TelegramBot appId=%s registered %d commands', this.applicationId, commands.length);
+ }
+
formatReply(body: string, stats?: UsageStats): string {
if (!stats || !this.config.settings?.showUsageStats) return body;
return `${body}\n\n${formatUsageStats(stats)}`;
diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.ts
index 4cc3ef29910..4cf1a21adfb 100644
--- a/src/server/services/bot/platforms/types.ts
+++ b/src/server/services/bot/platforms/types.ts
@@ -1,3 +1,5 @@
+import type { Chat } from 'chat';
+
// ============================================================================
// Bot Platform Core Types
// ============================================================================
@@ -85,6 +87,12 @@ export interface UsageStats {
*/
export interface PlatformClient {
readonly applicationId: string;
+ /**
+ * Apply platform-specific Chat SDK compatibility patches after bot initialization.
+ * Useful for adapter quirks that should stay encapsulated within the platform client.
+ */
+ applyChatPatches?: (chatBot: Chat<any>) => void;
+
/** Create a Chat SDK adapter config for inbound message handling. */
createAdapter: () => Record<string, any>;
@@ -109,6 +117,15 @@ export interface PlatformClient {
/** Parse a composite message ID into the platform-native format. */
parseMessageId: (compositeId: string) => string | number;
+ /**
+ * Register bot commands with the platform (e.g., Telegram setMyCommands).
+ * Called once during bot initialization with the list of available commands.
+ * Optional β€” platforms that don't support command menus can omit this.
+ */
+ registerBotCommands?: (
+ commands: Array<{ command: string; description: string }>,
+ ) => Promise<void>;
+
/**
* Resolve the correct thread ID for reaction API calls.
*
diff --git a/src/server/services/bot/replyTemplate.ts b/src/server/services/bot/replyTemplate.ts
index 8873dd1033a..05f9d25283f 100644
--- a/src/server/services/bot/replyTemplate.ts
+++ b/src/server/services/bot/replyTemplate.ts
@@ -192,6 +192,10 @@ export function renderError(errorMessage: string): string {
return `**Agent Execution Failed**\n\`\`\`\n${errorMessage}\n\`\`\``;
}
+export function renderStopped(message = 'Execution stopped.'): string {
+ return message;
+}
+
// ==================== Dispatcher ====================
/**