π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: telegram messager attachments (#15268)
Rdmclin281fc1aaf7f5a
diff --git a/src/server/routers/lambda/botMessage.ts b/src/server/routers/lambda/botMessage.tsindex 268ae81466d..7c9d67c1957 100644--- a/src/server/routers/lambda/botMessage.ts+++ b/src/server/routers/lambda/botMessage.ts@@ -11,8 +11,10 @@ import {import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { getMessengerTelegramConfig } from '@/config/messenger';import type { DecryptedBotProvider } from '@/database/models/agentBotProvider';import { AgentBotProviderModel } from '@/database/models/agentBotProvider';+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';import { MessengerInstallationModel } from '@/database/models/messengerInstallation';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -27,6 +29,7 @@ import { SlackMessageService } from '@/server/services/bot/platforms/slack/serviimport { TelegramApi } from '@/server/services/bot/platforms/telegram/api';import { TelegramMessageService } from '@/server/services/bot/platforms/telegram/service';import { WechatMessageService } from '@/server/services/bot/platforms/wechat/service';+import { TELEGRAM_INSTALLATION_KEY } from '@/server/services/messenger/installations/telegram';// ββ Middleware ββββββββββββββββββββββββββββββββββββββββββββ@@ -165,6 +168,38 @@ const resolveMessengerInstall = async (service: MessageRuntimeService;settings: Record<string, unknown>;}> => {+ // Telegram is env-backed and never lives in `messenger_installations`. The+ // synthetic id surfaced by `listMessengers` would 404 on `findById`, so+ // short-circuit here: pull the bot token from env config and gate on the+ // caller having an account link (analogue of the per-row ownership check).+ if (installationId === TELEGRAM_INSTALLATION_KEY) {+ const telegramConfig = await getMessengerTelegramConfig();+ if (!telegramConfig) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Telegram messenger is not configured on this deployment',+ });+ }+ const link = await new MessengerAccountLinkModel(ctx.serverDB, ctx.userId).findByPlatform(+ 'telegram',+ );+ if (!link) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message:+ 'You can only send through Telegram after linking your account. ' ++ 'Open the Telegram bot and run /start to create the link.',+ });+ }+ return {+ platform: 'telegram',+ service: createServiceForCredentials('telegram', TELEGRAM_INSTALLATION_KEY, {+ botToken: telegramConfig.botToken,+ }),+ settings: {},+ };+ }+const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);const row = await MessengerInstallationModel.findById(ctx.serverDB, installationId, gateKeeper);if (!row) {diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/message.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/message.test.tsindex d65cb5f990c..6f95b48bf7a 100644--- a/src/server/services/toolExecution/serverRuntimes/__tests__/message.test.ts+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/message.test.ts@@ -33,10 +33,12 @@ vi.mock('@/database/models/messengerInstallation', () => ({const mockLinkList = vi.fn();const mockLinkSetActiveAgent = vi.fn();const mockLinkDeleteByPlatform = vi.fn();+const mockLinkFindByPlatform = vi.fn();vi.mock('@/database/models/messengerAccountLink', () => ({MessengerAccountLinkModel: vi.fn().mockImplementation(() => ({deleteByPlatform: mockLinkDeleteByPlatform,+ findByPlatform: mockLinkFindByPlatform,list: mockLinkList,setActiveAgent: mockLinkSetActiveAgent,})),@@ -396,6 +398,47 @@ describe('messageRuntime', () => {});});+ describe('Telegram env-config fallback', () => {+ it('should fall back to env-backed config when no per-agent provider exists', async () => {+ mockQuery.mockResolvedValue([]);+ mockGetMessengerTelegramConfig.mockResolvedValueOnce({+ botToken: 'tg-env-token',+ botUsername: 'lobehub_bot',+ });+ mockTelegramSendMessage.mockResolvedValue({ message_id: 99 });++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.sendMessage({+ channelId: '-100999',+ content: 'Hello via env config!',+ platform: 'telegram',+ });++ expect(result.success).toBe(true);+ expect(result.state).toMatchObject({+ channelId: '-100999',+ messageId: '99',+ platform: 'telegram',+ });+ });++ it('should fail with descriptive error when neither per-agent nor env config exists', async () => {+ mockQuery.mockResolvedValue([]);+ mockGetMessengerTelegramConfig.mockResolvedValueOnce(null);++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.sendMessage({+ channelId: '-100999',+ content: 'Should fail',+ platform: 'telegram',+ });++ expect(result.success).toBe(false);+ expect(result.content).toContain('No enabled telegram bot provider found');+ expect(result.content).toContain('no env-backed Telegram config');+ });+ });+describe('dispatcher error handling', () => {it('should return error for unconfigured platform', async () => {mockQuery.mockResolvedValue([]);@@ -443,6 +486,7 @@ describe('messageRuntime', () => {mockLinkList,mockLinkSetActiveAgent,mockLinkDeleteByPlatform,+ mockLinkFindByPlatform,mockGetEnabledMessengerPlatforms,mockGetMessengerSlackConfig,mockGetMessengerDiscordConfig,@@ -498,6 +542,103 @@ describe('messageRuntime', () => {expect(result.content).toContain('No System Bot installations connected');expect(result.content).toContain('Settings β Messenger');});++ // Telegram is env-backed (no installation row); the runtime synthesizes a+ // virtual entry so the agent's two-step outbound discovery doesn't falsely+ // conclude Telegram is unconfigured while replying inside a Telegram chat.+ it('synthesizes a virtual telegram singleton when env+link both present', async () => {+ mockListByInstallerUserId.mockResolvedValueOnce([]);+ mockGetMessengerTelegramConfig.mockResolvedValueOnce({+ botToken: 'tg-env-token',+ botUsername: 'lobehub_bot',+ });+ mockLinkFindByPlatform.mockResolvedValueOnce({+ createdAt: new Date('2026-03-01T00:00:00Z'),+ platform: 'telegram',+ tenantId: '',+ userId: 'user-1',+ });++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.listMessengers({});++ expect(result.success).toBe(true);+ expect(result.state.installations).toHaveLength(1);+ expect(result.state.installations[0]).toMatchObject({+ applicationId: 'telegram:singleton',+ id: 'telegram:singleton',+ installedAt: '2026-03-01T00:00:00.000Z',+ platform: 'telegram',+ tenantId: '',+ tenantName: 'Telegram',+ });+ expect(mockLinkFindByPlatform).toHaveBeenCalledWith('telegram');+ });++ it('omits the telegram singleton when env config is missing', async () => {+ mockListByInstallerUserId.mockResolvedValueOnce([]);+ mockGetMessengerTelegramConfig.mockResolvedValueOnce(null);+ mockLinkFindByPlatform.mockResolvedValueOnce({+ createdAt: new Date('2026-03-01T00:00:00Z'),+ platform: 'telegram',+ tenantId: '',+ userId: 'user-1',+ });++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.listMessengers({});++ expect(result.success).toBe(true);+ expect(result.state.installations).toHaveLength(0);+ });++ it('omits the telegram singleton when the user has no telegram link', async () => {+ mockListByInstallerUserId.mockResolvedValueOnce([]);+ mockGetMessengerTelegramConfig.mockResolvedValueOnce({+ botToken: 'tg-env-token',+ botUsername: 'lobehub_bot',+ });+ mockLinkFindByPlatform.mockResolvedValueOnce(undefined);++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.listMessengers({});++ expect(result.success).toBe(true);+ expect(result.state.installations).toHaveLength(0);+ });++ it('appends the telegram singleton alongside real installs', async () => {+ mockListByInstallerUserId.mockResolvedValueOnce([+ {+ applicationId: 'app-slack',+ createdAt: new Date('2026-01-15T00:00:00Z'),+ id: 'inst_slack',+ metadata: { tenantName: 'Acme' },+ platform: 'slack',+ revokedAt: null,+ tenantId: 'T1',+ },+ ]);+ mockGetMessengerTelegramConfig.mockResolvedValueOnce({+ botToken: 'tg-env-token',+ botUsername: 'lobehub_bot',+ });+ mockLinkFindByPlatform.mockResolvedValueOnce({+ createdAt: new Date('2026-03-01T00:00:00Z'),+ platform: 'telegram',+ tenantId: '',+ userId: 'user-1',+ });++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.listMessengers({});++ expect(result.success).toBe(true);+ expect(result.state.installations.map((i: { id: string }) => i.id)).toEqual([+ 'inst_slack',+ 'telegram:singleton',+ ]);+ });});describe('System Bot β getMessengerDetail', () => {@@ -549,6 +690,43 @@ describe('messageRuntime', () => {expect(result.success).toBe(false);expect(result.content).toContain('not found');});++ it('synthesizes detail for the telegram singleton id', async () => {+ mockGetMessengerTelegramConfig.mockResolvedValueOnce({+ botToken: 'tg-env-token',+ botUsername: 'lobehub_bot',+ });+ mockLinkFindByPlatform.mockResolvedValueOnce({+ createdAt: new Date('2026-03-01T00:00:00Z'),+ platform: 'telegram',+ tenantId: '',+ userId: 'user-1',+ });++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.getMessengerDetail({ installationId: 'telegram:singleton' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('telegram:singleton');+ expect(result.content).toContain('Telegram');+ // Never hits the installations table for the singleton id.+ expect(mockFindInstallationById).not.toHaveBeenCalled();+ });++ it('returns null for telegram singleton when user has no link', async () => {+ mockGetMessengerTelegramConfig.mockResolvedValueOnce({+ botToken: 'tg-env-token',+ botUsername: 'lobehub_bot',+ });+ mockLinkFindByPlatform.mockResolvedValueOnce(undefined);++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.getMessengerDetail({ installationId: 'telegram:singleton' });++ // Same null-shaped response shape as a missing real install.+ expect(result.success).toBe(false);+ expect(result.content).toContain('not found');+ });});describe('System Bot β uninstallMessenger', () => {@@ -601,6 +779,18 @@ describe('messageRuntime', () => {expect(result.success).toBe(false);expect(result.content).toContain('not found');});++ it('rejects uninstall for the telegram singleton and steers caller to unlink', async () => {+ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.uninstallMessenger({ installationId: 'telegram:singleton' });++ expect(result.success).toBe(false);+ expect(result.content).toContain('Telegram is a global env-backed bot');+ expect(result.content).toContain('unlinkMessenger');+ // Must not have touched the installations table.+ expect(mockFindInstallationById).not.toHaveBeenCalled();+ expect(mockMarkRevoked).not.toHaveBeenCalled();+ });});describe('System Bot β listMessengerPlatforms', () => {diff --git a/src/server/services/toolExecution/serverRuntimes/message/index.ts b/src/server/services/toolExecution/serverRuntimes/message/index.tsindex b75c516bfac..6fbfb9a9108 100644--- a/src/server/services/toolExecution/serverRuntimes/message/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/message/index.ts@@ -38,10 +38,66 @@ import { WechatMessageService } from '@/server/services/bot/platforms/wechat/serimport { GatewayService } from '@/server/services/gateway';import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';import { messengerPlatformRegistry } from '@/server/services/messenger';+import { TELEGRAM_INSTALLATION_KEY } from '@/server/services/messenger/installations/telegram';import type { ServerRuntimeRegistration } from '../types';import { MessageDispatcherService } from './MessageDispatcherService';+/**+ * Shape returned by `listMessengers` / `getMessengerDetail` to the tool runtime.+ * Mirrors the public Z schema in builtin-tool-message; declared here so the+ * Telegram synthesis path produces an entry shape-identical to the DB-backed+ * rows without duplicating the column-mapping logic in three places.+ */+type MessengerInstallationView = {+ applicationId: string;+ enterpriseId: string | null;+ id: string;+ installedAt: string;+ isEnterpriseInstall: boolean;+ platform: string;+ scope: string;+ tenantId: string;+ tenantName: string;+};++/**+ * Telegram bots are env-backed singletons β they never get a row in+ * `messenger_installations` (see `installations/telegram.ts`). Without this+ * synthesis the agent's two-step outbound discovery (`listBots` β fallback+ * `listMessengers`) sees Telegram nowhere and falsely concludes the platform+ * is unconfigured, even while it is actively replying inside a Telegram chat.+ *+ * Returns a virtual install entry when both gates pass:+ * 1. Env has Telegram config (otherwise the singleton genuinely isn't set up)+ * 2. The current user has an account link for `platform='telegram'`+ * (otherwise the install exists globally but isn't routed to this user β+ * surfacing it would let any user send through a bot they haven't linked)+ */+const maybeSynthesizeTelegramInstall = async (+ serverDB: NonNullable<Parameters<typeof MessengerInstallationModel.listByInstallerUserId>[0]>,+ userId: string,+): Promise<MessengerInstallationView | undefined> => {+ const telegramConfig = await getMessengerTelegramConfig();+ if (!telegramConfig) return undefined;++ const link = await new MessengerAccountLinkModel(serverDB, userId).findByPlatform('telegram');+ if (!link) return undefined;++ return {+ applicationId: TELEGRAM_INSTALLATION_KEY,+ enterpriseId: null,+ id: TELEGRAM_INSTALLATION_KEY,+ installedAt:+ link.createdAt instanceof Date ? link.createdAt.toISOString() : String(link.createdAt),+ isEnterpriseInstall: false,+ platform: 'telegram',+ scope: '',+ tenantId: '',+ tenantName: 'Telegram',+ };+};+/*** Resolves credentials for the given platform from the user's configured bot providers.*/@@ -110,8 +166,21 @@ export const messageRuntime: ServerRuntimeRegistration = {return new SlackMessageService(new SlackApi(credentials.botToken));},telegram: async () => {- const { credentials } = await resolveCredentials(providerModel, 'telegram');- return new TelegramMessageService(new TelegramApi(credentials.botToken));+ // Per-agent provider takes precedence; fall back to the env-backed+ // singleton so the synthetic telegram:singleton install actually works.+ try {+ const { credentials } = await resolveCredentials(providerModel, 'telegram');+ return new TelegramMessageService(new TelegramApi(credentials.botToken));+ } catch {+ const envConfig = await getMessengerTelegramConfig();+ if (!envConfig) {+ throw new Error(+ 'No enabled telegram bot provider found and no env-backed Telegram config available. ' ++ 'Please configure a telegram integration in your bot settings.',+ );+ }+ return new TelegramMessageService(new TelegramApi(envConfig.botToken));+ }},wechat: async () => {const { applicationId, credentials } = await resolveCredentials(providerModel, 'wechat');@@ -256,7 +325,7 @@ export const messageRuntime: ServerRuntimeRegistration = {// `messenger.listMyInstallations` TRPC procedure runs. A stale Slack// install will still appear here; the actual send/uninstall call will// surface the underlying token error if and when it matters.- return rows+ const installations: MessengerInstallationView[] = rows.filter((row) => !row.revokedAt).map((row) => ({applicationId: row.applicationId,@@ -276,12 +345,31 @@ export const messageRuntime: ServerRuntimeRegistration = {tenantName:((row.metadata as Record<string, unknown> | null)?.tenantName as string) ?? '',}));++ const telegramView = await maybeSynthesizeTelegramInstall(+ context.serverDB,+ context.userId,+ );+ if (telegramView) installations.push(telegramView);++ return installations;},getMessengerDetail: async (installationId) => {if (!context.userId || !context.serverDB) {throw new Error('userId and serverDB are required to load installation');}+ // Telegram singleton has no DB row β synthesize the detail view from+ // env config + the caller's account link. Without this branch the+ // synthetic install id returned by `listMessengers` would 404 here.+ if (installationId === TELEGRAM_INSTALLATION_KEY) {+ const telegramView = await maybeSynthesizeTelegramInstall(+ context.serverDB,+ context.userId,+ );+ if (!telegramView) return null;+ return { ...telegramView, revokedAt: null };+ }const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);const row = await MessengerInstallationModel.findById(context.serverDB,@@ -320,6 +408,17 @@ export const messageRuntime: ServerRuntimeRegistration = {if (!context.userId || !context.serverDB) {throw new Error('userId and serverDB are required to uninstall');}+ // Telegram is env-backed and shared across all users β there is no+ // installation row to revoke. Direct callers to `unlinkMessenger`,+ // which removes only this user's routing without affecting anyone else.+ if (installationId === TELEGRAM_INSTALLATION_KEY) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message:+ 'Telegram is a global env-backed bot and cannot be uninstalled here. ' ++ "Use unlinkMessenger({ platform: 'telegram' }) to remove your own routing.",+ });+ }const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);const row = await MessengerInstallationModel.findById(context.serverDB,