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.

πŸ› fix: bot callback error (#13349)

Rdmclin2f4c4ba7db569
diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsx
index 63291a19b0e..67e929ebf5b 100644
--- a/src/routes/(main)/agent/channel/detail/Body.tsx
+++ b/src/routes/(main)/agent/channel/detail/Body.tsx
@@ -206,6 +206,7 @@ interface BodyProps {
currentConfig?: {
applicationId: string;
credentials: Record<string, string>;
+ settings?: Record<string, unknown> | null;
};
form: FormInstance<ChannelFormValues>;
hasConfig?: boolean;
diff --git a/src/routes/(main)/agent/channel/detail/formState.test.ts b/src/routes/(main)/agent/channel/detail/formState.test.ts
new file mode 100644
index 00000000000..d1f78ceed9a
--- /dev/null
+++ b/src/routes/(main)/agent/channel/detail/formState.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { getChannelFormValues } from './formState';
+
+describe('getChannelFormValues', () => {
+ it('should keep bot settings nested under the settings field', () => {
+ expect(
+ getChannelFormValues({
+ applicationId: 'bot-123',
+ credentials: { botToken: 'secret' },
+ settings: { debounceMs: 300, enableDM: true },
+ }),
+ ).toEqual({
+ applicationId: 'bot-123',
+ credentials: { botToken: 'secret' },
+ settings: { debounceMs: 300, enableDM: true },
+ });
+ });
+
+ it('should default missing nested objects to empty objects', () => {
+ expect(
+ getChannelFormValues({
+ applicationId: 'bot-123',
+ }),
+ ).toEqual({
+ applicationId: 'bot-123',
+ credentials: {},
+ settings: {},
+ });
+ });
+});
diff --git a/src/routes/(main)/agent/channel/detail/formState.ts b/src/routes/(main)/agent/channel/detail/formState.ts
new file mode 100644
index 00000000000..b64643dd7c2
--- /dev/null
+++ b/src/routes/(main)/agent/channel/detail/formState.ts
@@ -0,0 +1,20 @@
+interface ChannelConfigFormState {
+ applicationId?: string;
+ credentials?: Record<string, string>;
+ settings?: Record<string, unknown> | null;
+}
+
+interface ChannelFormSettings {
+ [key: string]: {} | undefined;
+}
+
+const normalizeSettings = (settings?: Record<string, unknown> | null): ChannelFormSettings =>
+ Object.fromEntries(
+ Object.entries(settings || {}).map(([key, value]) => [key, value ?? undefined]),
+ );
+
+export const getChannelFormValues = (config: ChannelConfigFormState) => ({
+ applicationId: config.applicationId || '',
+ credentials: config.credentials || {},
+ settings: normalizeSettings(config.settings),
+});
diff --git a/src/routes/(main)/agent/channel/detail/index.tsx b/src/routes/(main)/agent/channel/detail/index.tsx
index c9da6de16d3..b979df314d2 100644
--- a/src/routes/(main)/agent/channel/detail/index.tsx
+++ b/src/routes/(main)/agent/channel/detail/index.tsx
@@ -15,6 +15,7 @@ import {
} from '../../../../../types/botRuntimeStatus';
import Body from './Body';
import Footer from './Footer';
+import { getChannelFormValues } from './formState';
import Header from './Header';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -33,18 +34,22 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
+const omitUndefinedValues = <T extends Record<string, unknown>>(record: T) =>
+ Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T;
+
interface CurrentConfig {
applicationId: string;
credentials: Record<string, string>;
enabled: boolean;
id: string;
platform: string;
+ settings?: Record<string, unknown> | null;
}
export interface ChannelFormValues {
applicationId?: string;
credentials: Record<string, string>;
- settings: Record<string, unknown>;
+ settings: Record<string, {} | undefined>;
}
export interface TestResult {
@@ -188,10 +193,7 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren
// Sync form with saved config
useEffect(() => {
if (currentConfig) {
- form.setFieldsValue({
- applicationId: currentConfig.applicationId || '',
- credentials: currentConfig.credentials || {},
- } as any);
+ form.setFieldsValue(getChannelFormValues(currentConfig));
}
}, [currentConfig, form]);
@@ -229,7 +231,8 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren
const handleSave = useCallback(async () => {
try {
- const values = await form.validateFields();
+ await form.validateFields();
+ const values = form.getFieldsValue(true) as ChannelFormValues;
setSaving(true);
setSaveResult(undefined);
@@ -238,13 +241,14 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren
const {
applicationId: formAppId,
credentials: rawCredentials = {},
- settings = {},
+ settings: rawSettings = {},
} = values as ChannelFormValues;
// Strip undefined values from credentials (optional fields left empty by antd form)
const credentials = Object.fromEntries(
Object.entries(rawCredentials).filter(([, v]) => v !== undefined && v !== ''),
);
+ const settings = omitUndefinedValues(rawSettings);
// Use explicit applicationId from form; fall back to deriving from botToken (Telegram)
let applicationId = formAppId || '';
@@ -300,7 +304,7 @@ const PlatformDetail = memo<PlatformDetailProps>(({ platformDef, agentId, curren
try {
const { applicationId, credentials } = params;
- const settings = form.getFieldValue('settings') || {};
+ const settings = omitUndefinedValues(form.getFieldValue('settings') || {});
if (currentConfig) {
await updateBotProvider(currentConfig.id, agentId, {
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.ts
index a06135f9e50..e24e4904ef0 100644
--- a/src/server/services/bot/AgentBridgeService.ts
+++ b/src/server/services/bot/AgentBridgeService.ts
@@ -30,6 +30,10 @@ const log = debug('lobe-server:bot:agent-bridge');
const EXECUTION_TIMEOUT = 30 * 60 * 1000; // 30 minutes
+// PostgreSQL error code for foreign key constraint violations.
+// See: https://www.postgresql.org/docs/current/errcodes-appendix.html
+const PG_FOREIGN_KEY_VIOLATION = '23503';
+
// Status emoji added on receive, removed on complete
const RECEIVED_EMOJI = emoji.eyes;
@@ -282,8 +286,6 @@ export class AgentBridgeService {
const queueMode = isQueueAgentRuntimeEnabled();
let queueHandoffSucceeded = false;
- const platformThreadId = botContext?.platformThreadId ?? thread.id;
-
try {
// executeWithCallback handles progress message (post + edit at each step)
// The final reply is edited into the progress message by onComplete
@@ -362,8 +364,6 @@ export class AgentBridgeService {
);
await thread.startTyping();
- const platformThreadId = botContext?.platformThreadId ?? thread.id;
-
try {
// executeWithCallback handles progress message (post + edit at each step)
await this.executeWithCallback(thread, message, {
@@ -379,12 +379,16 @@ export class AgentBridgeService {
} catch (error) {
// If the cached topicId references a deleted topic (FK violation),
// clear thread state and retry as a fresh mention instead of surfacing the DB error.
+ const cause = (error as any)?.cause;
+ const isFKViolation =
+ cause?.code === PG_FOREIGN_KEY_VIOLATION && cause?.constraint?.includes('topic_id');
const errMsg = error instanceof Error ? error.message : String(error);
- if (errMsg.includes('Failed query') && errMsg.includes('topic_id')) {
+ if (isFKViolation) {
log(
'handleSubscribedMessage: stale topicId=%s, resetting and retrying as new mention',
topicId,
);
+ AgentBridgeService.activeThreads.delete(thread.id);
await thread.setState({ ...threadState, topicId: undefined });
return this.handleMention(thread, message, opts);
}
@@ -460,21 +464,13 @@ export class AgentBridgeService {
const aiAgentService = new AiAgentService(this.db, this.userId);
const timezone = await this.loadTimezone();
- const platformDef = platformRegistry.getPlatform(client?.id ?? '');
- const hasTyping = platformDef?.supportsTyping !== false;
+ await thread.startTyping();
let progressMessage: SentMessage | undefined;
-
- if (hasTyping) {
- // Platform supports typing β€” use typing indicator instead of an ack message.
- await thread.startTyping();
- } else {
- // No typing support β€” send a text acknowledgment so the user knows we received the message.
- try {
- progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
- } catch (error) {
- log('executeWithWebhooks: failed to post initial placeholder message: %O', error);
- }
+ try {
+ progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
+ } catch (error) {
+ log('executeWithWebhooks: failed to post initial placeholder message: %O', error);
}
const progressMessageId: string | undefined = progressMessage?.id;
@@ -530,6 +526,15 @@ export class AgentBridgeService {
}),
);
} catch (error) {
+ log('executeWithWebhooks: execAgent failed: %O', error);
+
+ // Rethrow FK violation errors (e.g. stale topic_id) so that callers like
+ // handleSubscribedMessage can detect and recover (reset thread state).
+ const cause = (error as any)?.cause;
+ if (cause?.code === PG_FOREIGN_KEY_VIOLATION) {
+ throw error;
+ }
+
await this.finishStartupFailure({
error,
progressMessage,
@@ -609,21 +614,13 @@ export class AgentBridgeService {
const aiAgentService = new AiAgentService(this.db, this.userId);
const timezone = await this.loadTimezone();
- const platformDef = platformRegistry.getPlatform(client?.id ?? '');
- const hasTyping = platformDef?.supportsTyping !== false;
+ await thread.startTyping();
let progressMessage: SentMessage | undefined;
-
- if (hasTyping) {
- // Platform supports typing β€” use typing indicator instead of an ack message.
- await thread.startTyping();
- } else {
- // No typing support β€” send a text acknowledgment so the user knows we received the message.
- try {
- progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
- } catch (error) {
- log('executeWithInMemoryCallbacks: failed to post initial placeholder message: %O', error);
- }
+ try {
+ progressMessage = await thread.post(renderStart(userMessage.text, { timezone }));
+ } catch (error) {
+ log('executeWithInMemoryCallbacks: failed to post initial placeholder message: %O', error);
}
// Track the last LLM content and tool calls for showing during tool execution
diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.ts
index 068498265e0..909148b69e3 100644
--- a/src/server/services/bot/BotCallbackService.ts
+++ b/src/server/services/bot/BotCallbackService.ts
@@ -209,7 +209,7 @@ export class BotCallbackService {
if (reason === 'error') {
const errorText = renderError(errorMessage || 'Agent execution failed');
try {
- if (canEdit) {
+ if (canEdit && progressMessageId) {
await messenger.editMessage(progressMessageId, errorText);
} else {
await messenger.createMessage(errorText);
@@ -250,13 +250,13 @@ export class BotCallbackService {
const chunks = splitMessage(finalText, charLimit);
try {
- if (canEdit) {
+ if (canEdit && progressMessageId) {
await messenger.editMessage(progressMessageId, chunks[0]);
for (let i = 1; i < chunks.length; i++) {
await messenger.createMessage(chunks[i]);
}
} else {
- // Platform doesn't support edit β€” send all chunks as new messages
+ // No progress message to edit or platform doesn't support edit β€” send all chunks as new messages
for (const chunk of chunks) {
await messenger.createMessage(chunk);
}
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index 789d677ebb4..ff9ab1f91a9 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -15,6 +15,7 @@ import {
type BotPlatformRuntimeContext,
type BotProviderConfig,
buildRuntimeKey,
+ mergeWithDefaults,
type PlatformClient,
type PlatformDefinition,
platformRegistry,
@@ -197,11 +198,24 @@ export class BotMessageRouter {
const platform = entry.id;
const key = buildRuntimeKey(platform, applicationId);
+ // Merge schema defaults with user settings (user overrides defaults)
+ const settings = mergeWithDefaults(
+ entry.schema,
+ provider.settings as Record<string, unknown> | undefined,
+ );
+
+ log(
+ 'createAndRegisterBot: %s settings merge: userSettings=%j, merged=%j',
+ key,
+ provider.settings,
+ settings,
+ );
+
const providerConfig: BotProviderConfig = {
applicationId,
credentials,
platform,
- settings: (provider.settings as Record<string, unknown>) || {},
+ settings,
};
const runtimeContext: BotPlatformRuntimeContext = {
@@ -214,9 +228,8 @@ export class BotMessageRouter {
const commands = this.buildCommands(serverDB, { agentId, platform, userId });
- const settings = provider.settings as Record<string, any> | undefined;
- const concurrencyStrategy = (settings?.concurrency as string) || 'debounce';
- const debounceMs = (settings?.debounceMs as number) || DEFAULT_DEBOUNCE_MS;
+ const concurrencyStrategy = (settings.concurrency as string) || 'debounce';
+ const debounceMs = (settings.debounceMs as number) || DEFAULT_DEBOUNCE_MS;
const chatBot = this.createChatBot(
adapters,
`agent-${agentId}`,
@@ -227,7 +240,7 @@ export class BotMessageRouter {
agentId,
applicationId,
platform,
- settings: provider.settings as Record<string, any> | undefined,
+ settings,
userId,
});
await chatBot.initialize();
diff --git a/src/server/services/bot/__tests__/BotMessageRouter.test.ts b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
index 5d91c35970a..0118be2ed4e 100644
--- a/src/server/services/bot/__tests__/BotMessageRouter.test.ts
+++ b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
@@ -69,6 +69,9 @@ vi.mock('../AgentBridgeService', () => ({
const mockCreateAdapter = vi.hoisted(() =>
vi.fn().mockReturnValue({ testplatform: { type: 'mock-adapter' } }),
);
+const mockMergeWithDefaults = vi.hoisted(() =>
+ vi.fn((_: unknown, settings?: Record<string, unknown>) => settings ?? {}),
+);
const mockGetPlatform = vi.hoisted(() =>
vi.fn().mockImplementation((platform: string) => {
@@ -100,6 +103,7 @@ const mockGetPlatform = vi.hoisted(() =>
vi.mock('../platforms', () => ({
buildRuntimeKey: (platform: string, appId: string) => `${platform}:${appId}`,
+ mergeWithDefaults: mockMergeWithDefaults,
platformRegistry: {
getPlatform: mockGetPlatform,
},
diff --git a/src/server/services/bot/platforms/feishu/definitions/feishu.ts b/src/server/services/bot/platforms/feishu/definitions/feishu.ts
index fd3e3f05d95..f1fd90c1f02 100644
--- a/src/server/services/bot/platforms/feishu/definitions/feishu.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/feishu.ts
@@ -13,6 +13,5 @@ export const feishu: PlatformDefinition = {
schema: sharedSchema,
showWebhookUrl: true,
supportsMarkdown: false,
- supportsTyping: false,
clientFactory: sharedClientFactory,
};
diff --git a/src/server/services/bot/platforms/feishu/definitions/lark.ts b/src/server/services/bot/platforms/feishu/definitions/lark.ts
index c882f03408e..e798e3ae1af 100644
--- a/src/server/services/bot/platforms/feishu/definitions/lark.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/lark.ts
@@ -13,6 +13,5 @@ export const lark: PlatformDefinition = {
schema: sharedSchema,
showWebhookUrl: true,
supportsMarkdown: false,
- supportsTyping: false,
clientFactory: sharedClientFactory,
};
diff --git a/src/server/services/bot/platforms/index.ts b/src/server/services/bot/platforms/index.ts
index 0cbcf980f3e..bed6b9bf8b5 100644
--- a/src/server/services/bot/platforms/index.ts
+++ b/src/server/services/bot/platforms/index.ts
@@ -30,6 +30,7 @@ export {
formatDuration,
formatTokens,
formatUsageStats,
+ mergeWithDefaults,
parseRuntimeKey,
} from './utils';
diff --git a/src/server/services/bot/platforms/qq/definition.ts b/src/server/services/bot/platforms/qq/definition.ts
index aa13fbe2b88..5db9dadd2f2 100644
--- a/src/server/services/bot/platforms/qq/definition.ts
+++ b/src/server/services/bot/platforms/qq/definition.ts
@@ -14,6 +14,5 @@ export const qq: PlatformDefinition = {
showWebhookUrl: true,
supportsMarkdown: false,
supportsMessageEdit: false,
- supportsTyping: false,
clientFactory: new QQClientFactory(),
};
diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.ts
index aefe9034ef6..0d6eee31709 100644
--- a/src/server/services/bot/platforms/types.ts
+++ b/src/server/services/bot/platforms/types.ts
@@ -294,14 +294,6 @@ export interface PlatformDefinition {
* Defaults to true.
*/
supportsMessageEdit?: boolean;
-
- /**
- * Whether the platform supports typing indicators for bots.
- * When true, a typing indicator is shown instead of posting an acknowledgment message.
- * When false, a text acknowledgment ("Late night vibes.", etc.) is sent immediately.
- * Defaults to true.
- */
- supportsTyping?: boolean;
}
/** Serialized platform definition for frontend consumption (excludes runtime-only fields). */
diff --git a/src/server/services/bot/platforms/utils.ts b/src/server/services/bot/platforms/utils.ts
index abe0cc374df..b622ee9afa9 100644
--- a/src/server/services/bot/platforms/utils.ts
+++ b/src/server/services/bot/platforms/utils.ts
@@ -1,3 +1,5 @@
+import { merge } from '@lobechat/utils';
+
import type { FieldSchema, UsageStats } from './types';
// --------------- Settings defaults ---------------
@@ -21,9 +23,6 @@ function extractFieldDefault(field: FieldSchema): unknown {
* Extract defaults from a FieldSchema array.
*
* Recursively walks the fields and collects all `default` values.
- * Use this to merge with user-provided settings at runtime:
- *
- * const settings = { ...extractDefaults(definition.settings), ...provider.settings };
*/
export function extractDefaults(fields?: FieldSchema[]): Record<string, unknown> {
if (!fields) return {};
@@ -35,6 +34,22 @@ export function extractDefaults(fields?: FieldSchema[]): Record<string, unknown>
return result;
}
+/**
+ * Merge platform schema defaults with user-provided settings.
+ * Extracts defaults from the schema, then deep-merges with user overrides.
+ *
+ * const settings = mergeWithDefaults(entry.schema, provider.settings);
+ */
+export function mergeWithDefaults(
+ schema: FieldSchema[],
+ userSettings?: Record<string, unknown> | null,
+): Record<string, unknown> {
+ const settingsSchema = schema.find((f) => f.key === 'settings')?.properties;
+ const defaults = extractDefaults(settingsSchema);
+ if (!userSettings) return defaults;
+ return merge(defaults, userSettings) as Record<string, unknown>;
+}
+
// --------------- Runtime key helpers ---------------
/**
diff --git a/src/store/agent/slices/bot/action.ts b/src/store/agent/slices/bot/action.ts
index aea6b923ea1..5af46bb96ce 100644
--- a/src/store/agent/slices/bot/action.ts
+++ b/src/store/agent/slices/bot/action.ts
@@ -21,6 +21,7 @@ export interface BotProviderItem {
enabled: boolean;
id: string;
platform: string;
+ settings?: Record<string, unknown> | null;
}
type Setter = StoreSetter<AgentStore>;