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.

✨ feat: localize bot connection errors (#17029)

Rdmclin2e3a2f0594a8c
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.md
index 981baa30c81..a0aacdb243e 100644
--- a/.agents/skills/agent-testing/references/common-mistakes.md
+++ b/.agents/skills/agent-testing/references/common-mistakes.md
@@ -7,6 +7,24 @@
---
+## Case 18 — Treating a status badge as proof that the error message rendered
+
+**Wrong approach**: marking an error-state UI case as passed because the platform page showed
+the `Failed` badge, while the screenshot only contained an unrelated configuration reminder
+and did not show the error alert or its translated message.
+
+**Why it's wrong**: the badge proves only that a failed runtime state reached the page. It does
+not prove that `errorCode` was translated and presented to the user, which is the core assertion
+of an error-message verification.
+
+**What it breaks**: a report can claim that users receive an actionable explanation while its
+visual evidence shows no explanation at all.
+
+**Correct approach**: for an error-presentation case, visually require all three signals in the
+same screenshot: the target platform, the failed status, and the error alert containing the
+expected user-facing message. Any unrelated warning or setup reminder does not satisfy the
+error-message assertion.
+
## Case 1 — Judging `passed` from heuristics instead of looking at the screenshot
**Wrong approach**: after navigating to a surface, deciding "renders fine /
diff --git a/apps/server/src/services/gateway/MessageGatewayClient.ts b/apps/server/src/services/gateway/MessageGatewayClient.ts
index 03d45357641..b6c23594ab9 100644
--- a/apps/server/src/services/gateway/MessageGatewayClient.ts
+++ b/apps/server/src/services/gateway/MessageGatewayClient.ts
@@ -22,6 +22,7 @@ export interface MessageGatewayConnectionStatus {
config: { connectionId: string; platform: string } | null;
state: {
connectedAt?: number;
+ errorCode?: string;
error?: string;
platform: string;
status: 'connected' | 'connecting' | 'disconnected' | 'dormant' | 'error';
diff --git a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
index 31f5c202b9f..3a684b2cd82 100644
--- a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
+++ b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
@@ -30,13 +30,16 @@ const mockGatewayManager = vi.hoisted(() => ({
}));
const mockFindEnabledByPlatform = vi.hoisted(() => vi.fn());
+const mockFindByAgentId = vi.hoisted(() => vi.fn());
const mockFindByIds = vi.hoisted(() => vi.fn());
+const mockFindEnabledByPlatformAndAppId = vi.hoisted(() => vi.fn());
const mockGetServerDB = vi.hoisted(() => vi.fn());
const mockInitWithEnvKey = vi.hoisted(() => vi.fn());
const mockUpdateBotRuntimeStatus = vi.hoisted(() => vi.fn());
const mockResolveConnectionMode = vi.hoisted(() => vi.fn());
const mockIsBotFeatureAccessAllowed = vi.hoisted(() => vi.fn());
const mockGetBotFeatureBlockedMessage = vi.hoisted(() => vi.fn());
+const mockGetBotRuntimeStatus = vi.hoisted(() => vi.fn());
// ─── Module mocks ───
@@ -59,8 +62,10 @@ vi.mock('@/database/core/db-adaptor', () => ({
vi.mock('@/database/models/agentBotProvider', () => ({
AgentBotProviderModel: {
+ findByAgentId: mockFindByAgentId,
findByIds: mockFindByIds,
findEnabledByPlatform: mockFindEnabledByPlatform,
+ findEnabledByPlatformAndAppId: mockFindEnabledByPlatformAndAppId,
},
}));
@@ -76,6 +81,7 @@ vi.mock('../runtimeStatus', () => ({
queued: 'queued',
starting: 'starting',
},
+ getBotRuntimeStatus: mockGetBotRuntimeStatus,
updateBotRuntimeStatus: mockUpdateBotRuntimeStatus,
}));
@@ -104,7 +110,9 @@ describe('GatewayService', () => {
mockGetServerDB.mockResolvedValue({});
mockInitWithEnvKey.mockResolvedValue({});
mockFindEnabledByPlatform.mockResolvedValue([]);
+ mockFindByAgentId.mockResolvedValue([]);
mockFindByIds.mockResolvedValue([]);
+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(null);
// Default: admin snapshot unavailable → sync falls back to per-connection
// getStatus and skips stale-connection cleanup (matches pre-reconciliation behavior).
mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));
@@ -112,6 +120,7 @@ describe('GatewayService', () => {
mockUpdateBotRuntimeStatus.mockResolvedValue({});
mockIsBotFeatureAccessAllowed.mockResolvedValue(true);
mockGetBotFeatureBlockedMessage.mockReturnValue('This bot channel requires a paid plan.');
+ mockGetBotRuntimeStatus.mockResolvedValue({});
service = new GatewayService();
});
@@ -129,6 +138,55 @@ describe('GatewayService', () => {
});
});
+ describe('runtime status refresh', () => {
+ beforeEach(() => {
+ mockGatewayClient.isEnabled = true;
+ mockResolveConnectionMode.mockReturnValue('websocket');
+ });
+
+ it('preserves gateway error codes during a single refresh', async () => {
+ mockFindEnabledByPlatformAndAppId.mockResolvedValue({ id: 'prov-1', settings: {} });
+ mockGatewayClient.getStatus.mockResolvedValue({
+ state: { error: 'invalid token', errorCode: 'invalid_credentials', status: 'error' },
+ });
+
+ await service.refreshBotRuntimeStatus('discord', 'app-1');
+
+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({
+ applicationId: 'app-1',
+ errorCode: 'invalid_credentials',
+ errorMessage: 'invalid token',
+ platform: 'discord',
+ status: 'failed',
+ });
+ });
+
+ it('preserves gateway error codes during an agent-wide refresh', async () => {
+ mockFindByAgentId.mockResolvedValue([
+ {
+ applicationId: 'app-1',
+ enabled: true,
+ id: 'prov-1',
+ platform: 'discord',
+ settings: {},
+ },
+ ]);
+ mockGatewayClient.getStatus.mockResolvedValue({
+ state: { error: 'invalid token', errorCode: 'invalid_credentials', status: 'error' },
+ });
+
+ await service.refreshBotRuntimeStatusesByAgent('agent-1');
+
+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({
+ applicationId: 'app-1',
+ errorCode: 'invalid_credentials',
+ errorMessage: 'invalid token',
+ platform: 'discord',
+ status: 'failed',
+ });
+ });
+ });
+
// ─── ensureRunning ───
describe('ensureRunning', () => {
diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.ts
index 3098a92767f..29f6e88fd4c 100644
--- a/apps/server/src/services/gateway/index.ts
+++ b/apps/server/src/services/gateway/index.ts
@@ -642,6 +642,7 @@ export class GatewayService {
const { state } = await client.getStatus(provider.id);
await updateBotRuntimeStatus({
applicationId: provider.applicationId,
+ errorCode: state.errorCode,
errorMessage: state.error,
platform: provider.platform,
status: mapGatewayStatusToRuntimeStatus(state.status),
@@ -695,6 +696,7 @@ export class GatewayService {
const { state } = await client.getStatus(provider.id);
return await updateBotRuntimeStatus({
applicationId,
+ errorCode: state.errorCode,
errorMessage: state.error,
platform,
status: mapGatewayStatusToRuntimeStatus(state.status),
diff --git a/apps/server/src/services/gateway/runtimeStatus.test.ts b/apps/server/src/services/gateway/runtimeStatus.test.ts
index a4a46c817a2..bef463f3309 100644
--- a/apps/server/src/services/gateway/runtimeStatus.test.ts
+++ b/apps/server/src/services/gateway/runtimeStatus.test.ts
@@ -55,6 +55,33 @@ describe('runtimeStatus', () => {
);
});
+ it('persists a stable error code alongside the diagnostic message', async () => {
+ mockRedis.set.mockResolvedValue('OK');
+
+ await updateBotRuntimeStatus(
+ {
+ applicationId: 'app-1',
+ errorCode: 'invalid_credentials',
+ errorMessage: 'QQ auth rejected: code=100016',
+ platform: 'qq',
+ status: BOT_RUNTIME_STATUSES.failed,
+ },
+ { now: 123 },
+ );
+
+ expect(mockRedis.set).toHaveBeenCalledWith(
+ 'bot:runtime-status:qq:app-1',
+ JSON.stringify({
+ applicationId: 'app-1',
+ errorCode: 'invalid_credentials',
+ errorMessage: 'QQ auth rejected: code=100016',
+ platform: 'qq',
+ status: BOT_RUNTIME_STATUSES.failed,
+ updatedAt: 123,
+ }),
+ );
+ });
+
it('cleans malformed runtime status payloads', async () => {
mockRedis.get.mockResolvedValue('{bad-json');
mockRedis.del.mockResolvedValue(1);
diff --git a/apps/server/src/services/gateway/runtimeStatus.ts b/apps/server/src/services/gateway/runtimeStatus.ts
index c5b6a903725..9211aad484e 100644
--- a/apps/server/src/services/gateway/runtimeStatus.ts
+++ b/apps/server/src/services/gateway/runtimeStatus.ts
@@ -14,6 +14,7 @@ export type { BotRuntimeStatus, BotRuntimeStatusSnapshot };
interface UpdateBotRuntimeStatusParams {
applicationId: string;
+ errorCode?: string;
errorMessage?: string;
platform: string;
status: BotRuntimeStatus;
@@ -81,6 +82,7 @@ export async function updateBotRuntimeStatus(
const redisClient = options.redisClient ?? getAgentRuntimeRedisClient();
const snapshot: BotRuntimeStatusSnapshot = {
applicationId: params.applicationId,
+ errorCode: params.errorCode,
errorMessage: params.errorMessage,
platform: params.platform,
status: params.status,
diff --git a/locales/ar/agent.json b/locales/ar/agent.json
index c3b7b85d864..0ad617e3ea5 100644
--- a/locales/ar/agent.json
+++ b/locales/ar/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "تم الاتصال بالروبوت بنجاح",
"channel.connecting": "جارٍ الاتصال...",
"channel.connectionConfig": "إعدادات الاتصال",
+ "channel.connectionError.application_not_found": "تطبيق الروبوت غير موجود. تحقق من معرف التطبيق في وحدة تحكم المنصة.",
+ "channel.connectionError.connection_closed": "تم انقطاع الاتصال بالمنصة. سيحاول LobeHub إعادة الاتصال تلقائيًا.",
+ "channel.connectionError.invalid_credentials": "بيانات اعتماد الروبوت غير صالحة. تحقق من معرف التطبيق، السر، ورموز الوصول.",
+ "channel.connectionError.missing_credentials": "بيانات اعتماد الروبوت المطلوبة مفقودة. أكمل إعداد القناة وحاول مرة أخرى.",
+ "channel.connectionError.permission_denied": "تم رفض الوصول من قبل المنصة. تحقق من أذونات الروبوت والقدرات المفعلة.",
+ "channel.connectionError.rate_limited": "المنصة تحد من معدل استخدام هذا الروبوت. انتظر لحظة وحاول مرة أخرى.",
+ "channel.connectionError.session_expired": "انتهت صلاحية جلسة الروبوت. احفظ القناة مرة أخرى لإعادة الاتصال.",
+ "channel.connectionError.upstream_unavailable": "خدمة المنصة غير متوفرة مؤقتًا. سيحاول LobeHub مرة أخرى لاحقًا.",
"channel.connectionMode": "وضع الاتصال",
"channel.connectionModeHint": "يُفضَّل استخدام WebSocket للروبوتات الجديدة. استخدم Webhook إذا كان روبوتك يحتوي بالفعل على عنوان URL مُعدّ لرد النداء على منصة QQ المفتوحة.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/bg-BG/agent.json b/locales/bg-BG/agent.json
index 2b8d5f9fd8a..20e46a80a0b 100644
--- a/locales/bg-BG/agent.json
+++ b/locales/bg-BG/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Ботът е успешно свързан",
"channel.connecting": "Свързване...",
"channel.connectionConfig": "Конфигурация на връзката",
+ "channel.connectionError.application_not_found": "Приложението на бота не съществува. Проверете идентификатора на приложението в конзолата на платформата.",
+ "channel.connectionError.connection_closed": "Връзката с платформата беше прекъсната. LobeHub ще се опита да се свърже автоматично отново.",
+ "channel.connectionError.invalid_credentials": "Удостоверителните данни на бота са невалидни. Проверете идентификатора на приложението, тайния ключ и токените за достъп.",
+ "channel.connectionError.missing_credentials": "Липсват необходимите удостоверителни данни за бота. Завършете конфигурацията на канала и опитайте отново.",
+ "channel.connectionError.permission_denied": "Платформата отказа достъп. Проверете разрешенията и активираните възможности на бота.",
+ "channel.connectionError.rate_limited": "Платформата ограничава скоростта на този бот. Изчакайте малко и опитайте отново.",
+ "channel.connectionError.session_expired": "Сесията на бота е изтекла. Запазете канала отново, за да го свържете.",
+ "channel.connectionError.upstream_unavailable": "Услугата на платформата временно не е налична. LobeHub ще опита отново по-късно.",
"channel.connectionMode": "Режим на свързване",
"channel.connectionModeHint": "WebSocket се препоръчва за нови ботове. Използвайте Webhook, ако вашият бот вече има конфигуриран callback URL в платформата QQ Open Platform.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/de-DE/agent.json b/locales/de-DE/agent.json
index 6f19575f9ce..a6d23ae6089 100644
--- a/locales/de-DE/agent.json
+++ b/locales/de-DE/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot erfolgreich verbunden",
"channel.connecting": "Verbinden...",
"channel.connectionConfig": "Verbindungskonfiguration",
+ "channel.connectionError.application_not_found": "Die Bot-Anwendung existiert nicht. Überprüfen Sie die Anwendungs-ID in der Plattformkonsole.",
+ "channel.connectionError.connection_closed": "Die Verbindung zur Plattform wurde unterbrochen. LobeHub wird versuchen, automatisch erneut zu verbinden.",
+ "channel.connectionError.invalid_credentials": "Die Bot-Anmeldedaten sind ungültig. Überprüfen Sie die Anwendungs-ID, das Geheimnis und die Zugriffstoken.",
+ "channel.connectionError.missing_credentials": "Erforderliche Bot-Anmeldedaten fehlen. Vervollständigen Sie die Kanalkonfiguration und versuchen Sie es erneut.",
+ "channel.connectionError.permission_denied": "Der Zugriff wurde von der Plattform verweigert. Überprüfen Sie die Berechtigungen und aktivierten Funktionen des Bots.",
+ "channel.connectionError.rate_limited": "Die Plattform begrenzt die Rate dieses Bots. Warten Sie einen Moment und versuchen Sie es erneut.",
+ "channel.connectionError.session_expired": "Die Bot-Sitzung ist abgelaufen. Speichern Sie den Kanal erneut, um ihn wieder zu verbinden.",
+ "channel.connectionError.upstream_unavailable": "Der Plattformdienst ist vorübergehend nicht verfügbar. LobeHub wird es später erneut versuchen.",
"channel.connectionMode": "Verbindungsmodus",
"channel.connectionModeHint": "Für neue Bots wird WebSocket empfohlen. Verwenden Sie Webhook, wenn Ihr Bot bereits über eine konfigurierte Callback-URL auf der QQ Open Platform verfügt.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index e35c1c17098..dae2ab076d1 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot connected successfully",
"channel.connecting": "Connecting...",
"channel.connectionConfig": "Connection Configuration",
+ "channel.connectionError.application_not_found": "The bot application does not exist. Check the application ID in the platform console.",
+ "channel.connectionError.connection_closed": "The platform connection was interrupted. LobeHub will try to reconnect automatically.",
+ "channel.connectionError.invalid_credentials": "The bot credentials are invalid. Check the application ID, secret, and access tokens.",
+ "channel.connectionError.missing_credentials": "Required bot credentials are missing. Complete the channel configuration and try again.",
+ "channel.connectionError.permission_denied": "The platform denied access. Check the bot's permissions and enabled capabilities.",
+ "channel.connectionError.rate_limited": "The platform is rate limiting this bot. Wait a moment and try again.",
+ "channel.connectionError.session_expired": "The bot session has expired. Save the channel again to reconnect it.",
+ "channel.connectionError.upstream_unavailable": "The platform service is temporarily unavailable. LobeHub will try again later.",
"channel.connectionMode": "Connection Mode",
"channel.connectionModeHint": "How the platform delivers events to the bot",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/es-ES/agent.json b/locales/es-ES/agent.json
index f76957f1cef..7c36e57bd86 100644
--- a/locales/es-ES/agent.json
+++ b/locales/es-ES/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot conectado exitosamente",
"channel.connecting": "Conectando...",
"channel.connectionConfig": "Configuración de Conexión",
+ "channel.connectionError.application_not_found": "La aplicación del bot no existe. Verifica el ID de la aplicación en la consola de la plataforma.",
+ "channel.connectionError.connection_closed": "La conexión con la plataforma fue interrumpida. LobeHub intentará reconectarse automáticamente.",
+ "channel.connectionError.invalid_credentials": "Las credenciales del bot son inválidas. Verifica el ID de la aplicación, el secreto y los tokens de acceso.",
+ "channel.connectionError.missing_credentials": "Faltan las credenciales requeridas del bot. Completa la configuración del canal e inténtalo de nuevo.",
+ "channel.connectionError.permission_denied": "La plataforma denegó el acceso. Verifica los permisos y las capacidades habilitadas del bot.",
+ "channel.connectionError.rate_limited": "La plataforma está limitando la tasa de este bot. Espera un momento e inténtalo de nuevo.",
+ "channel.connectionError.session_expired": "La sesión del bot ha expirado. Guarda el canal nuevamente para reconectarlo.",
+ "channel.connectionError.upstream_unavailable": "El servicio de la plataforma está temporalmente no disponible. LobeHub intentará nuevamente más tarde.",
"channel.connectionMode": "Modo de conexión",
"channel.connectionModeHint": "Se recomienda WebSocket para los bots nuevos. Use Webhook si su bot ya tiene una URL de callback configurada en la Plataforma Abierta de QQ.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/fa-IR/agent.json b/locales/fa-IR/agent.json
index 0afd69fadb1..94aab4c4911 100644
--- a/locales/fa-IR/agent.json
+++ b/locales/fa-IR/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "ربات با موفقیت متصل شد",
"channel.connecting": "در حال اتصال...",
"channel.connectionConfig": "پیکربندی اتصال",
+ "channel.connectionError.application_not_found": "برنامه ربات وجود ندارد. شناسه برنامه را در کنسول پلتفرم بررسی کنید.",
+ "channel.connectionError.connection_closed": "اتصال پلتفرم قطع شده است. LobeHub به صورت خودکار تلاش خواهد کرد دوباره متصل شود.",
+ "channel.connectionError.invalid_credentials": "اعتبارنامه‌های ربات نامعتبر هستند. شناسه برنامه، رمز و توکن‌های دسترسی را بررسی کنید.",
+ "channel.connectionError.missing_credentials": "اعتبارنامه‌های ضروری ربات وجود ندارند. پیکربندی کانال را کامل کنید و دوباره تلاش کنید.",
+ "channel.connectionError.permission_denied": "پلتفرم دسترسی را رد کرده است. مجوزها و قابلیت‌های فعال شده ربات را بررسی کنید.",
+ "channel.connectionError.rate_limited": "پلتفرم محدودیت نرخ برای این ربات اعمال کرده است. کمی صبر کنید و دوباره تلاش کنید.",
+ "channel.connectionError.session_expired": "جلسه ربات منقضی شده است. کانال را دوباره ذخیره کنید تا دوباره متصل شود.",
+ "channel.connectionError.upstream_unavailable": "سرویس پلتفرم به طور موقت در دسترس نیست. LobeHub بعداً دوباره تلاش خواهد کرد.",
"channel.connectionMode": "حالت اتصال",
"channel.connectionModeHint": "وب‌سوکت برای ربات‌های جدید توصیه می‌شود. اگر ربات شما از قبل یک نشانی callback در پلتفرم QQ Open دارد، از وب‌هوک استفاده کنید.",
"channel.connectionModeWebSocket": "وب‌سوکت",
diff --git a/locales/fr-FR/agent.json b/locales/fr-FR/agent.json
index f06d0377148..efb16cd3fc8 100644
--- a/locales/fr-FR/agent.json
+++ b/locales/fr-FR/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot connecté avec succès",
"channel.connecting": "Connexion en cours...",
"channel.connectionConfig": "Configuration de la connexion",
+ "channel.connectionError.application_not_found": "L'application du bot n'existe pas. Vérifiez l'ID de l'application dans la console de la plateforme.",
+ "channel.connectionError.connection_closed": "La connexion à la plateforme a été interrompue. LobeHub tentera de se reconnecter automatiquement.",
+ "channel.connectionError.invalid_credentials": "Les identifiants du bot sont invalides. Vérifiez l'ID de l'application, le secret et les jetons d'accès.",
+ "channel.connectionError.missing_credentials": "Les identifiants requis du bot sont manquants. Complétez la configuration du canal et réessayez.",
+ "channel.connectionError.permission_denied": "La plateforme a refusé l'accès. Vérifiez les permissions et les capacités activées du bot.",
+ "channel.connectionError.rate_limited": "La plateforme applique une limitation de débit à ce bot. Attendez un moment et réessayez.",
+ "channel.connectionError.session_expired": "La session du bot a expiré. Enregistrez à nouveau le canal pour le reconnecter.",
+ "channel.connectionError.upstream_unavailable": "Le service de la plateforme est temporairement indisponible. LobeHub réessaiera plus tard.",
"channel.connectionMode": "Mode de connexion",
"channel.connectionModeHint": "Le mode WebSocket est recommandé pour les nouveaux bots. Utilisez Webhook si votre bot possède déjà une URL de rappel configurée sur la plateforme QQ Open Platform.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/it-IT/agent.json b/locales/it-IT/agent.json
index a6e895a13b1..afecd8491cf 100644
--- a/locales/it-IT/agent.json
+++ b/locales/it-IT/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot connesso con successo",
"channel.connecting": "Connessione in corso...",
"channel.connectionConfig": "Configurazione Connessione",
+ "channel.connectionError.application_not_found": "L'applicazione del bot non esiste. Controlla l'ID dell'applicazione nella console della piattaforma.",
+ "channel.connectionError.connection_closed": "La connessione alla piattaforma è stata interrotta. LobeHub tenterà di riconnettersi automaticamente.",
+ "channel.connectionError.invalid_credentials": "Le credenziali del bot non sono valide. Controlla l'ID dell'applicazione, il segreto e i token di accesso.",
+ "channel.connectionError.missing_credentials": "Le credenziali richieste del bot sono mancanti. Completa la configurazione del canale e riprova.",
+ "channel.connectionError.permission_denied": "L'accesso è stato negato dalla piattaforma. Controlla i permessi del bot e le funzionalità abilitate.",
+ "channel.connectionError.rate_limited": "La piattaforma sta limitando la velocità di questo bot. Attendi un momento e riprova.",
+ "channel.connectionError.session_expired": "La sessione del bot è scaduta. Salva nuovamente il canale per riconnetterlo.",
+ "channel.connectionError.upstream_unavailable": "Il servizio della piattaforma è temporaneamente non disponibile. LobeHub tenterà nuovamente più tardi.",
"channel.connectionMode": "Modalità di connessione",
"channel.connectionModeHint": "Si consiglia WebSocket per i nuovi bot. Usa Webhook se il tuo bot ha già un URL di callback configurato sulla Piattaforma Open di QQ.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/ja-JP/agent.json b/locales/ja-JP/agent.json
index 8287924c933..653fda1c1bc 100644
--- a/locales/ja-JP/agent.json
+++ b/locales/ja-JP/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "ボットが正常に接続されました",
"channel.connecting": "接続中...",
"channel.connectionConfig": "接続設定",
+ "channel.connectionError.application_not_found": "ボットアプリケーションが存在しません。プラットフォームコンソールでアプリケーションIDを確認してください。",
+ "channel.connectionError.connection_closed": "プラットフォーム接続が中断されました。LobeHubは自動的に再接続を試みます。",
+ "channel.connectionError.invalid_credentials": "ボットの認証情報が無効です。アプリケーションID、シークレット、およびアクセストークンを確認してください。",
+ "channel.connectionError.missing_credentials": "必要なボットの認証情報が不足しています。チャンネル設定を完了して、再試行してください。",
+ "channel.connectionError.permission_denied": "プラットフォームがアクセスを拒否しました。ボットの権限と有効な機能を確認してください。",
+ "channel.connectionError.rate_limited": "プラットフォームがこのボットをレート制限しています。少し待ってから再試行してください。",
+ "channel.connectionError.session_expired": "ボットセッションが期限切れになりました。チャンネルを再保存して再接続してください。",
+ "channel.connectionError.upstream_unavailable": "プラットフォームサービスが一時的に利用できません。LobeHubは後で再試行します。",
"channel.connectionMode": "接続モード",
"channel.connectionModeHint": "新しいボットには WebSocket を推奨します。すでに QQ オープンプラットフォームでコールバック URL を設定済みの場合は Webhook を使用してください。",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/ko-KR/agent.json b/locales/ko-KR/agent.json
index c78ba5042e5..200bcce2fc5 100644
--- a/locales/ko-KR/agent.json
+++ b/locales/ko-KR/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "봇 연결 성공",
"channel.connecting": "연결 중...",
"channel.connectionConfig": "연결 구성",
+ "channel.connectionError.application_not_found": "봇 애플리케이션이 존재하지 않습니다. 플랫폼 콘솔에서 애플리케이션 ID를 확인하세요.",
+ "channel.connectionError.connection_closed": "플랫폼 연결이 중단되었습니다. LobeHub이 자동으로 다시 연결을 시도합니다.",
+ "channel.connectionError.invalid_credentials": "봇 자격 증명이 유효하지 않습니다. 애플리케이션 ID, 비밀키, 액세스 토큰을 확인하세요.",
+ "channel.connectionError.missing_credentials": "필수 봇 자격 증명이 누락되었습니다. 채널 구성을 완료하고 다시 시도하세요.",
+ "channel.connectionError.permission_denied": "플랫폼에서 접근이 거부되었습니다. 봇의 권한과 활성화된 기능을 확인하세요.",
+ "channel.connectionError.rate_limited": "플랫폼이 이 봇의 요청을 제한하고 있습니다. 잠시 기다렸다가 다시 시도하세요.",
+ "channel.connectionError.session_expired": "봇 세션이 만료되었습니다. 채널을 다시 저장하여 재연결하세요.",
+ "channel.connectionError.upstream_unavailable": "플랫폼 서비스가 일시적으로 사용할 수 없습니다. LobeHub이 나중에 다시 시도할 것입니다.",
"channel.connectionMode": "연결 모드",
"channel.connectionModeHint": "새로운 봇에는 WebSocket을 권장합니다. 이미 QQ 오픈 플랫폼에서 콜백 URL이 설정된 경우 Webhook을 사용하세요.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/nl-NL/agent.json b/locales/nl-NL/agent.json
index f982ff89f76..f755a89c9e6 100644
--- a/locales/nl-NL/agent.json
+++ b/locales/nl-NL/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot succesvol verbonden",
"channel.connecting": "Verbinden...",
"channel.connectionConfig": "Verbindingsconfiguratie",
+ "channel.connectionError.application_not_found": "De botapplicatie bestaat niet. Controleer de applicatie-ID in de platformconsole.",
+ "channel.connectionError.connection_closed": "De platformverbinding is onderbroken. LobeHub zal automatisch proberen opnieuw verbinding te maken.",
+ "channel.connectionError.invalid_credentials": "De botreferenties zijn ongeldig. Controleer de applicatie-ID, geheim en toegangstokens.",
+ "channel.connectionError.missing_credentials": "Vereiste botreferenties ontbreken. Voltooi de kanaalconfiguratie en probeer het opnieuw.",
+ "channel.connectionError.permission_denied": "Het platform heeft de toegang geweigerd. Controleer de machtigingen en ingeschakelde mogelijkheden van de bot.",
+ "channel.connectionError.rate_limited": "Het platform beperkt de snelheid van deze bot. Wacht een moment en probeer het opnieuw.",
+ "channel.connectionError.session_expired": "De botsessie is verlopen. Sla het kanaal opnieuw op om opnieuw verbinding te maken.",
+ "channel.connectionError.upstream_unavailable": "De platformservice is tijdelijk niet beschikbaar. LobeHub zal het later opnieuw proberen.",
"channel.connectionMode": "Verbindingsmodus",
"channel.connectionModeHint": "WebSocket wordt aanbevolen voor nieuwe bots. Gebruik Webhook als je bot al een callback-URL heeft ingesteld op het QQ Open Platform.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/pl-PL/agent.json b/locales/pl-PL/agent.json
index e6ea5344664..90532076370 100644
--- a/locales/pl-PL/agent.json
+++ b/locales/pl-PL/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot połączony pomyślnie",
"channel.connecting": "Łączenie...",
"channel.connectionConfig": "Konfiguracja połączenia",
+ "channel.connectionError.application_not_found": "Aplikacja bota nie istnieje. Sprawdź identyfikator aplikacji w konsoli platformy.",
+ "channel.connectionError.connection_closed": "Połączenie z platformą zostało przerwane. LobeHub spróbuje automatycznie nawiązać połączenie ponownie.",
+ "channel.connectionError.invalid_credentials": "Dane uwierzytelniające bota są nieprawidłowe. Sprawdź identyfikator aplikacji, sekret i tokeny dostępu.",
+ "channel.connectionError.missing_credentials": "Brak wymaganych danych uwierzytelniających bota. Uzupełnij konfigurację kanału i spróbuj ponownie.",
+ "channel.connectionError.permission_denied": "Platforma odmówiła dostępu. Sprawdź uprawnienia bota i włączone funkcje.",
+ "channel.connectionError.rate_limited": "Platforma ogranicza szybkość działania tego bota. Poczekaj chwilę i spróbuj ponownie.",
+ "channel.connectionError.session_expired": "Sesja bota wygasła. Zapisz kanał ponownie, aby nawiązać połączenie.",
+ "channel.connectionError.upstream_unavailable": "Usługa platformy jest tymczasowo niedostępna. LobeHub spróbuje ponownie później.",
"channel.connectionMode": "Tryb połączenia",
"channel.connectionModeHint": "WebSocket jest zalecany dla nowych botów. Użyj Webhook, jeśli Twój bot ma już skonfigurowany adres URL wywołania zwrotnego na platformie QQ Open Platform.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/pt-BR/agent.json b/locales/pt-BR/agent.json
index 3ad94054adb..cc52dfea805 100644
--- a/locales/pt-BR/agent.json
+++ b/locales/pt-BR/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot conectado com sucesso",
"channel.connecting": "Conectando...",
"channel.connectionConfig": "Configuração de Conexão",
+ "channel.connectionError.application_not_found": "A aplicação do bot não existe. Verifique o ID da aplicação no console da plataforma.",
+ "channel.connectionError.connection_closed": "A conexão com a plataforma foi interrompida. O LobeHub tentará se reconectar automaticamente.",
+ "channel.connectionError.invalid_credentials": "As credenciais do bot são inválidas. Verifique o ID da aplicação, o segredo e os tokens de acesso.",
+ "channel.connectionError.missing_credentials": "Credenciais obrigatórias do bot estão ausentes. Complete a configuração do canal e tente novamente.",
+ "channel.connectionError.permission_denied": "A plataforma negou acesso. Verifique as permissões do bot e as capacidades habilitadas.",
+ "channel.connectionError.rate_limited": "A plataforma está limitando a taxa deste bot. Aguarde um momento e tente novamente.",
+ "channel.connectionError.session_expired": "A sessão do bot expirou. Salve o canal novamente para reconectá-lo.",
+ "channel.connectionError.upstream_unavailable": "O serviço da plataforma está temporariamente indisponível. O LobeHub tentará novamente mais tarde.",
"channel.connectionMode": "Modo de Conexão",
"channel.connectionModeHint": "WebSocket é recomendado para novos bots. Use Webhook se seu bot já tiver um URL de callback configurado na Plataforma Aberta do QQ.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/ru-RU/agent.json b/locales/ru-RU/agent.json
index c01afa4677a..b3a51d5219c 100644
--- a/locales/ru-RU/agent.json
+++ b/locales/ru-RU/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Бот успешно подключен",
"channel.connecting": "Подключение...",
"channel.connectionConfig": "Конфигурация подключения",
+ "channel.connectionError.application_not_found": "Приложение бота не существует. Проверьте идентификатор приложения в консоли платформы.",
+ "channel.connectionError.connection_closed": "Соединение с платформой было прервано. LobeHub попытается автоматически переподключиться.",
+ "channel.connectionError.invalid_credentials": "Учетные данные бота недействительны. Проверьте идентификатор приложения, секретный ключ и токены доступа.",
+ "channel.connectionError.missing_credentials": "Отсутствуют необходимые учетные данные бота. Завершите настройку канала и попробуйте снова.",
+ "channel.connectionError.permission_denied": "Платформа отказала в доступе. Проверьте разрешения бота и включенные возможности.",
+ "channel.connectionError.rate_limited": "Платформа ограничивает частоту запросов этого бота. Подождите немного и попробуйте снова.",
+ "channel.connectionError.session_expired": "Сессия бота истекла. Сохраните канал снова, чтобы переподключить его.",
+ "channel.connectionError.upstream_unavailable": "Сервис платформы временно недоступен. LobeHub попробует снова позже.",
"channel.connectionMode": "Режим подключения",
"channel.connectionModeHint": "Для новых ботов рекомендуется WebSocket. Используйте Webhook, если для вашего бота уже настроен URL обратного вызова на платформе QQ Open Platform.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/tr-TR/agent.json b/locales/tr-TR/agent.json
index e12984b5c1a..47e13a782cf 100644
--- a/locales/tr-TR/agent.json
+++ b/locales/tr-TR/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot başarıyla bağlandı",
"channel.connecting": "Bağlanıyor...",
"channel.connectionConfig": "Bağlantı Yapılandırması",
+ "channel.connectionError.application_not_found": "Bot uygulaması mevcut değil. Platform konsolunda uygulama kimliğini kontrol edin.",
+ "channel.connectionError.connection_closed": "Platform bağlantısı kesildi. LobeHub otomatik olarak yeniden bağlanmaya çalışacak.",
+ "channel.connectionError.invalid_credentials": "Bot kimlik bilgileri geçersiz. Uygulama kimliğini, gizli anahtarı ve erişim tokenlerini kontrol edin.",
+ "channel.connectionError.missing_credentials": "Gerekli bot kimlik bilgileri eksik. Kanal yapılandırmasını tamamlayın ve tekrar deneyin.",
+ "channel.connectionError.permission_denied": "Platform erişimi reddetti. Botun izinlerini ve etkinleştirilmiş yeteneklerini kontrol edin.",
+ "channel.connectionError.rate_limited": "Platform bu botu hız sınırlamasına tabi tutuyor. Bir süre bekleyin ve tekrar deneyin.",
+ "channel.connectionError.session_expired": "Bot oturumu sona erdi. Kanalı yeniden bağlamak için tekrar kaydedin.",
+ "channel.connectionError.upstream_unavailable": "Platform hizmeti geçici olarak kullanılamıyor. LobeHub daha sonra tekrar deneyecek.",
"channel.connectionMode": "Bağlantı Modu",
"channel.connectionModeHint": "Yeni botlar için WebSocket önerilir. Botunuz QQ Açık Platformunda zaten yapılandırılmış bir geri çağırma URL’sine sahipse Webhook kullanın.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/vi-VN/agent.json b/locales/vi-VN/agent.json
index 4ed6be61f83..35830b77bc4 100644
--- a/locales/vi-VN/agent.json
+++ b/locales/vi-VN/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Kết nối bot thành công",
"channel.connecting": "Đang kết nối...",
"channel.connectionConfig": "Cấu hình kết nối",
+ "channel.connectionError.application_not_found": "Ứng dụng bot không tồn tại. Kiểm tra ID ứng dụng trong bảng điều khiển nền tảng.",
+ "channel.connectionError.connection_closed": "Kết nối với nền tảng đã bị gián đoạn. LobeHub sẽ tự động thử kết nối lại.",
+ "channel.connectionError.invalid_credentials": "Thông tin xác thực của bot không hợp lệ. Kiểm tra ID ứng dụng, mã bí mật và mã truy cập.",
+ "channel.connectionError.missing_credentials": "Thiếu thông tin xác thực cần thiết của bot. Hoàn thành cấu hình kênh và thử lại.",
+ "channel.connectionError.permission_denied": "Nền tảng đã từ chối quyền truy cập. Kiểm tra quyền và các khả năng được kích hoạt của bot.",
+ "channel.connectionError.rate_limited": "Nền tảng đang giới hạn tốc độ của bot này. Vui lòng đợi một lúc và thử lại.",
+ "channel.connectionError.session_expired": "Phiên làm việc của bot đã hết hạn. Lưu kênh lại để kết nối lại.",
+ "channel.connectionError.upstream_unavailable": "Dịch vụ nền tảng tạm thời không khả dụng. LobeHub sẽ thử lại sau.",
"channel.connectionMode": "Chế độ kết nối",
"channel.connectionModeHint": "WebSocket được kh推荐 sử dụng cho các bot mới. Dùng Webhook nếu bot của bạn đã cấu hình sẵn URL callback trên Nền tảng Mở QQ.",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 59d73b6b4f6..abe7356554e 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "Bot 连接成功",
"channel.connecting": "连接中...",
"channel.connectionConfig": "连接配置",
+ "channel.connectionError.application_not_found": "机器人应用不存在,请检查平台控制台中的应用 ID。",
+ "channel.connectionError.connection_closed": "平台连接已中断,LobeHub 将自动尝试重连。",
+ "channel.connectionError.invalid_credentials": "机器人凭据无效,请检查应用 ID、密钥和访问令牌。",
+ "channel.connectionError.missing_credentials": "缺少必要的机器人凭据,请补全频道配置后重试。",
+ "channel.connectionError.permission_denied": "平台拒绝了访问,请检查机器人的权限和已启用能力。",
+ "channel.connectionError.rate_limited": "平台正在限制该机器人的请求频率,请稍后重试。",
+ "channel.connectionError.session_expired": "机器人会话已过期,请重新保存频道配置以建立连接。",
+ "channel.connectionError.upstream_unavailable": "平台服务暂时不可用,LobeHub 稍后会自动重试。",
"channel.connectionMode": "连接模式",
"channel.connectionModeHint": "平台向机器人推送事件的方式",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/locales/zh-TW/agent.json b/locales/zh-TW/agent.json
index 3137e6cccff..abe687cf8f7 100644
--- a/locales/zh-TW/agent.json
+++ b/locales/zh-TW/agent.json
@@ -36,6 +36,14 @@
"channel.connectSuccess": "機器人成功連線",
"channel.connecting": "正在連線...",
"channel.connectionConfig": "連接配置",
+ "channel.connectionError.application_not_found": "機器人應用程式不存在。請檢查平台控制台中的應用程式 ID。",
+ "channel.connectionError.connection_closed": "平台連線已中斷。LobeHub 將自動嘗試重新連線。",
+ "channel.connectionError.invalid_credentials": "機器人憑證無效。請檢查應用程式 ID、密鑰和存取權杖。",
+ "channel.connectionError.missing_credentials": "缺少必要的機器人憑證。請完成頻道設定後再試一次。",
+ "channel.connectionError.permission_denied": "平台拒絕了存取權限。請檢查機器人的權限和已啟用的功能。",
+ "channel.connectionError.rate_limited": "平台正在限制此機器人的請求頻率。請稍候再試一次。",
+ "channel.connectionError.session_expired": "機器人會話已過期。請重新儲存頻道以重新連線。",
+ "channel.connectionError.upstream_unavailable": "平台服務暫時無法使用。LobeHub 將稍後再試。",
"channel.connectionMode": "連線模式",
"channel.connectionModeHint": "若為新機器人,建議使用 WebSocket。若您的機器人在 QQ 開放平台上已設定回呼網址,請使用 Webhook。",
"channel.connectionModeWebSocket": "WebSocket",
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 1e7f0b369b0..d155b04a600 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -69,6 +69,22 @@ export default {
'channel.connectStarting': 'Bot is starting. Please wait a moment.',
'channel.connectSuccess': 'Bot connected successfully',
'channel.connecting': 'Connecting...',
+ 'channel.connectionError.application_not_found':
+ 'The bot application does not exist. Check the application ID in the platform console.',
+ 'channel.connectionError.connection_closed':
+ 'The platform connection was interrupted. LobeHub will try to reconnect automatically.',
+ 'channel.connectionError.invalid_credentials':
+ 'The bot credentials are invalid. Check the application ID, secret, and access tokens.',
+ 'channel.connectionError.missing_credentials':
+ 'Required bot credentials are missing. Complete the channel configuration and try again.',
+ 'channel.connectionError.permission_denied':
+ "The platform denied access. Check the bot's permissions and enabled capabilities.",
+ 'channel.connectionError.rate_limited':
+ 'The platform is rate limiting this bot. Wait a moment and try again.',
+ 'channel.connectionError.session_expired':
+ 'The bot session has expired. Save the channel again to reconnect it.',
+ 'channel.connectionError.upstream_unavailable':
+ 'The platform service is temporarily unavailable. LobeHub will try again later.',
'channel.endpointUrl': 'Webhook URL',
'channel.endpointUrlHint':
'Please copy this URL and paste it into the <bold>{{fieldName}}</bold> field in the {{name}} Developer Portal.',
diff --git a/src/routes/(main)/agent/channel/detail/index.tsx b/src/routes/(main)/agent/channel/detail/index.tsx
index db8ec59e8b9..af558109f3e 100644
--- a/src/routes/(main)/agent/channel/detail/index.tsx
+++ b/src/routes/(main)/agent/channel/detail/index.tsx
@@ -153,7 +153,11 @@ const PlatformDetail = memo<PlatformDetailProps>(
}
case BOT_RUNTIME_STATUSES.failed: {
return {
- errorDetail: runtimeStatus.errorMessage,
+ errorDetail: runtimeStatus.errorCode
+ ? t(`channel.connectionError.${runtimeStatus.errorCode}`, {
+ defaultValue: runtimeStatus.errorMessage || t('channel.connectFailed'),
+ })
+ : runtimeStatus.errorMessage,
title: t('channel.connectFailed'),
type: 'error',
};
diff --git a/src/server/agent-hono/handlers/__tests__/gatewayCallback.test.ts b/src/server/agent-hono/handlers/__tests__/gatewayCallback.test.ts
index 9e1ccc0e8d8..413ceb5cb44 100644
--- a/src/server/agent-hono/handlers/__tests__/gatewayCallback.test.ts
+++ b/src/server/agent-hono/handlers/__tests__/gatewayCallback.test.ts
@@ -142,7 +142,7 @@ describe('gatewayCallback handler', () => {
authHeader: 'Bearer token-xyz',
body: {
...validBody,
- state: { error: 'oops', status: incoming },
+ state: { error: 'oops', errorCode: 'invalid_credentials', status: incoming },
},
});
@@ -152,6 +152,7 @@ describe('gatewayCallback handler', () => {
expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledTimes(1);
expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({
applicationId: 'app-1',
+ errorCode: 'invalid_credentials',
errorMessage: 'oops',
platform: 'discord',
status: expected,
diff --git a/src/server/agent-hono/handlers/gatewayCallback.ts b/src/server/agent-hono/handlers/gatewayCallback.ts
index 8d8a2cf06f8..611b7522a4b 100644
--- a/src/server/agent-hono/handlers/gatewayCallback.ts
+++ b/src/server/agent-hono/handlers/gatewayCallback.ts
@@ -16,6 +16,7 @@ const StateChangeSchema = z.object({
connectionId: z.string(),
platform: z.string(),
state: z.object({
+ errorCode: z.string().optional(),
error: z.string().optional(),
status: z.enum(['connected', 'connecting', 'disconnected', 'dormant', 'error']),
}),
@@ -80,6 +81,7 @@ export async function gatewayCallback(c: Context): Promise<Response> {
await updateBotRuntimeStatus({
applicationId,
+ errorCode: state.errorCode,
errorMessage: state.error,
platform,
status: runtimeStatus,
diff --git a/src/types/botRuntimeStatus.ts b/src/types/botRuntimeStatus.ts
index 4a632584602..979e1c36a5e 100644
--- a/src/types/botRuntimeStatus.ts
+++ b/src/types/botRuntimeStatus.ts
@@ -13,6 +13,8 @@ export type BotRuntimeStatus = (typeof BOT_RUNTIME_STATUSES)[keyof typeof BOT_RU
export interface BotRuntimeStatusSnapshot {
applicationId: string;
+ /** Stable cross-platform gateway error code for client-side i18n. */
+ errorCode?: string;
errorMessage?: string;
platform: string;
status: BotRuntimeStatus;