🤯 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
✨ feat(telegram): support Guest Mode summons without joining the chat (#18846)
XYenona19bfe7d239a
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/messengerWebhook.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/messengerWebhook.test.tsnew file mode 100644index 00000000000..f813f0eba50--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/__tests__/messengerWebhook.test.ts@@ -0,0 +1,41 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { messengerWebhook } from '../messengerWebhook';++const { mockGetMessengerRouter, mockGetWebhookHandler } = vi.hoisted(() => {+ const getWebhookHandler = vi.fn();+ return {+ mockGetMessengerRouter: vi.fn(() => ({ getWebhookHandler })),+ mockGetWebhookHandler: getWebhookHandler,+ };+});++vi.mock('@/server/services/messenger', () => ({+ getMessengerRouter: mockGetMessengerRouter,+}));++describe('messengerWebhook handler', () => {+ it('passes a waitUntil option to the Messenger router', async () => {+ const rawRequest = new Request('http://x/api/agent/messenger/webhooks/telegram', {+ body: '{}',+ method: 'POST',+ });+ const response = new Response('ok');+ const handler = vi.fn().mockResolvedValue(response);+ mockGetWebhookHandler.mockReturnValue(handler);+ const context = {+ req: {+ param: (name: string) => (name === 'platform' ? 'telegram' : undefined),+ raw: rawRequest,+ url: rawRequest.url,+ },+ } as any;++ await expect(messengerWebhook(context)).resolves.toBe(response);+ expect(mockGetWebhookHandler).toHaveBeenCalledWith('telegram');+ expect(handler).toHaveBeenCalledWith(rawRequest, {+ waitUntil: expect.any(Function),+ });+ });+});diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/platformWebhook.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/platformWebhook.test.tsindex c6f54639897..20d68b728a5 100644--- a/apps/server/src/router-hono/agent/handlers/__tests__/platformWebhook.test.ts+++ b/apps/server/src/router-hono/agent/handlers/__tests__/platformWebhook.test.ts@@ -71,6 +71,9 @@ describe('platformWebhook handler', () => {// so the handler must receive `c.req.raw` verbatim.expect(innerHandler).toHaveBeenCalledTimes(1);expect(innerHandler.mock.calls[0][0]).toBe(rawRequest);+ expect(innerHandler.mock.calls[0][1]).toEqual({+ waitUntil: expect.any(Function),+ });});it('passes appId=undefined when only platform is provided', async () => {diff --git a/apps/server/src/router-hono/agent/handlers/messengerWebhook.ts b/apps/server/src/router-hono/agent/handlers/messengerWebhook.tsindex 85dd1c1a07d..3464c96f98c 100644--- a/apps/server/src/router-hono/agent/handlers/messengerWebhook.ts+++ b/apps/server/src/router-hono/agent/handlers/messengerWebhook.ts@@ -2,6 +2,7 @@ import debug from 'debug';import type { Context } from 'hono';import { getMessengerRouter } from '@/server/services/messenger';+import { after } from '@/server/utils/scheduleAfterResponse';const log = debug('lobe-server:messenger:webhook-route');@@ -26,5 +27,5 @@ export async function messengerWebhook(c: Context): Promise<Response> {const router = getMessengerRouter();const handler = router.getWebhookHandler(platform);- return handler(c.req.raw);+ return handler(c.req.raw, { waitUntil: (task) => after(() => task) });}diff --git a/apps/server/src/router-hono/agent/handlers/platformWebhook.ts b/apps/server/src/router-hono/agent/handlers/platformWebhook.tsindex 7a687ee06cf..4a1597be493 100644--- a/apps/server/src/router-hono/agent/handlers/platformWebhook.ts+++ b/apps/server/src/router-hono/agent/handlers/platformWebhook.ts@@ -2,6 +2,7 @@ import debug from 'debug';import type { Context } from 'hono';import { getBotMessageRouter } from '@/server/services/bot';+import { after } from '@/server/utils/scheduleAfterResponse';const log = debug('lobe-server:bot:webhook-route');@@ -26,5 +27,5 @@ export async function platformWebhook(c: Context): Promise<Response> {const router = getBotMessageRouter();const handler = router.getWebhookHandler(platform, appId);- return handler(c.req.raw);+ return handler(c.req.raw, { waitUntil: (task) => after(() => task) });}diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 85c0be8a312..72d6e3e5af8 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -53,7 +53,7 @@ import {isLobeAiAgentSlug,resolveAgentSelfIterationCapability,} from '@/server/services/agentSignal/featureGate';-import { platformRegistry } from '@/server/services/bot/platforms';+import { resolveUnsupportedMessageApis } from '@/server/services/bot/platforms/messageCapabilities';import type { ComposioService } from '@/server/services/composio';import {buildLastSyncedAtMap,@@ -832,13 +832,16 @@ export const discoverTools = async (// in the sandbox.// For bot conversations we also pass the IM platform so `lobe-message`// can drop APIs the platform can't fulfil (e.g. WeChat has no- // `readMessages`).+ // `readMessages`). Telegram Guest Mode uses a stricter overlay —+ // the bot is not a chat member and has no regular channel tools.manifestContext: {...(botContext?.platform && {botPlatform: {id: botContext.platform,- unsupportedMessageApis: platformRegistry.getPlatform(botContext.platform)- ?.unsupportedMessageApis,+ unsupportedMessageApis: resolveUnsupportedMessageApis(+ botContext.platform,+ botContext.platformThreadId,+ ),},}),executionEnv: executionPlanToManifestExecutionEnv(executionPlan, localDeviceId),diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.tsindex 3db9e8d0329..2db6b69e82f 100644--- a/apps/server/src/services/bot/AgentBridgeService.ts+++ b/apps/server/src/services/bot/AgentBridgeService.ts@@ -28,6 +28,7 @@ import {RECEIVED_REACTION_EMOJI,THINKING_REACTION_EMOJI,} from './platforms';+import { resolveUnsupportedMessageApis } from './platforms/messageCapabilities';import { clearReactionState, saveReactionState } from './reactionState';import { buildRecentChannelHistory } from './recentChannelHistory';import { renderThrownAgentError } from './renderThrownError';@@ -749,10 +750,12 @@ export class AgentBridgeService {// Platforms whose runtime rejects `readMessages` (e.g. WeChat) can't fetch// history on demand. We flag that so the prompt stops telling the model to// call `readMessages`, and instead pre-inject recent same-channel history- // below (see `buildRecentChannelHistory`).- const canReadHistory = !platformDef?.unsupportedMessageApis?.includes(- MessageApiName.readMessages,- );+ // below (see `buildRecentChannelHistory`). Guest Telegram summons use the+ // guest overlay (no channel tools, including history).+ const canReadHistory = !resolveUnsupportedMessageApis(+ opts.botContext?.platform,+ opts.botContext?.platformThreadId,+ )?.includes(MessageApiName.readMessages);const botPlatformContext: BotPlatformContext | undefined = platformDef? {canReadHistory,diff --git a/apps/server/src/services/bot/BotMessageRouter.ts b/apps/server/src/services/bot/BotMessageRouter.tsindex 25ff2d35698..0761c70137b 100644--- a/apps/server/src/services/bot/BotMessageRouter.ts+++ b/apps/server/src/services/bot/BotMessageRouter.ts@@ -1,6 +1,7 @@import { createIoRedisState } from '@chat-adapter/state-ioredis';import { DEFAULT_BOT_DEBOUNCE_MS } from '@lobechat/const';-import { Chat, ConsoleLogger, type Message, type MessageContext } from 'chat';+import type { Message, MessageContext, WebhookOptions } from 'chat';+import { Chat, ConsoleLogger } from 'chat';import debug from 'debug';import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';@@ -33,11 +34,14 @@ import {type DmSettings,extractDmSettings,extractGroupSettings,+ extractGuestSettings,extractUserAllowlist,extractWatchKeywordEntries,findMatchingWatchKeywordEntries,getBotReplyLocale,type GroupSettings,+ type GuestDecision,+ type GuestSettings,messageMatchesWatchKeyword,normalizeAllowFromEntries,normalizeBotReplyLocale,@@ -48,9 +52,11 @@ import {shouldAllowSender,shouldHandleDm,shouldHandleGroup,+ shouldHandleGuest,type UserAllowlist,type WatchKeywordEntry,} from './platforms';+import { isGuestTelegramThreadId } from './platforms/telegram/threadId';import { renderThrownAgentError } from './renderThrownError';import {renderApproveSuccess,@@ -59,6 +65,8 @@ import {renderDmRejected,renderFeedbackSubmitted,renderGroupRejected,+ renderGuestPairing,+ renderGuestRejected,renderInlineError,renderModeStatus,renderSenderRejected,@@ -211,8 +219,11 @@ export class BotMessageRouter {* Get the webhook handler for a given platform + appId.* Returns a function compatible with Next.js Route Handler: `(req: Request) => Promise<Response>`*/- getWebhookHandler(platform: string, appId?: string): (req: Request) => Promise<Response> {- return async (req: Request) => {+ getWebhookHandler(+ platform: string,+ appId?: string,+ ): (req: Request, options?: WebhookOptions) => Promise<Response> {+ return async (req: Request, options?: WebhookOptions) => {const entry = platformRegistry.getPlatform(platform);if (!entry) {return new Response('No bot configured for this platform', { status: 404 });@@ -222,7 +233,7 @@ export class BotMessageRouter {return new Response(`Missing appId for ${platform} webhook`, { status: 400 });}- return this.handleWebhook(req, platform, appId);+ return this.handleWebhook(req, platform, appId, options);};}@@ -243,7 +254,12 @@ export class BotMessageRouter {// Webhook handling// ------------------------------------------------------------------- private async handleWebhook(req: Request, platform: string, appId: string): Promise<Response> {+ private async handleWebhook(+ req: Request,+ platform: string,+ appId: string,+ options?: WebhookOptions,+ ): Promise<Response> {log('handleWebhook: platform=%s, appId=%s', platform, appId);const bot = await this.getOrCreateBot(platform, appId);@@ -252,7 +268,7 @@ export class BotMessageRouter {}if (bot.chatBot.webhooks && platform in bot.chatBot.webhooks) {- const response: Response = await (bot.chatBot.webhooks as any)[platform](req);+ const response: Response = await (bot.chatBot.webhooks as any)[platform](req, options);if (response.status === 401)await this.reconcileWebhookAfterRejection(platform, appId, bot.client);return response;@@ -418,12 +434,12 @@ export class BotMessageRouter {const client = entry.clientFactory.createClient(providerConfig, runtimeContext);const adapters = client.createAdapter();- // dmSettings + operatorUserId are needed by `/approve` (to enforce the- // owner-only gate and to know whether pairing is even enabled), and by- // the DM pairing branch in registerHandlers. Extract once, share with- // both — registerHandlers re-derives from `settings` to keep its own- // closure-internal contract self-contained.+ // Access settings + operatorUserId are needed by `/approve` (to enforce+ // the owner-only gate and to know whether pairing is enabled), and by+ // registerHandlers. Extract once, share with commands; registerHandlers+ // re-derives from `settings` to keep its closure self-contained.const dmSettings: DmSettings = extractDmSettings(settings);+ const guestSettings: GuestSettings = extractGuestSettings(settings);const operatorUserId =typeof settings.userId === 'string'? (settings.userId as string).trim() || undefined@@ -434,6 +450,7 @@ export class BotMessageRouter {applicationId,client,dmSettings,+ guestSettings,operatorUserId,platform,providerId: provider.id,@@ -632,6 +649,7 @@ export class BotMessageRouter {const charLimit = (info.settings?.charLimit as number) || undefined;const displayToolCalls = info.settings?.displayToolCalls === true;const dmSettings: DmSettings = extractDmSettings(info.settings);+ const guestSettings: GuestSettings = extractGuestSettings(info.settings);const groupSettings: GroupSettings = extractGroupSettings(info.settings);const userAllowlist: UserAllowlist = extractUserAllowlist(info.settings);/**@@ -737,6 +755,18 @@ export class BotMessageRouter {userAllowlist,});+ const passesGuestPolicy = (+ thread: { id: string },+ message: { author?: { userId?: string } },+ ): GuestDecision =>+ shouldHandleGuest({+ authorUserId: message.author?.userId,+ guestSettings,+ isGuest: platform === 'telegram' && isGuestTelegramThreadId(thread.id),+ operatorUserId,+ userAllowlist,+ });+/*** Gate inbound events on group policy. DM threads pass through — they* are governed by `passesDmPolicy` instead. Non-DM threads are blocked@@ -756,8 +786,11 @@ export class BotMessageRouter {* not the parent operators pasted. `extraGroupAllowlistChannels`* surfaces the parent so either ID lets the message through.*/- const passesGroupPolicy = (thread: { id: string; isDM?: boolean }): boolean =>- shouldHandleGroup({+ const passesGroupPolicy = (thread: { id: string; isDM?: boolean }): boolean => {+ // Guest Mode has its own user-scoped policy. It remains separate from+ // Group Policy because the bot has not joined the source chat.+ if (platform === 'telegram' && isGuestTelegramThreadId(thread.id)) return true;+ return shouldHandleGroup({candidateChannelIds: [client.extractChatId(thread.id),...(client.extraGroupAllowlistChannels?.(thread.id) ?? []),@@ -765,6 +798,7 @@ export class BotMessageRouter {groupSettings,isDM: thread.isDM === true,});+ };/*** Handle a sender that the global `allowFrom` rejected. Posts the@@ -807,7 +841,7 @@ export class BotMessageRouter {replyLocale: BotReplyLocale,): Promise<void> => {// 'open' and 'pairing' should never reach here ('pairing' has its own- // flow via triggerDmPairing), but guard anyway so we never post the+ // flow via triggerPairing), but guard anyway so we never post the// wrong copy if shouldHandleDm grows another false branch.if (dmSettings.policy !== 'allowlist' && dmSettings.policy !== 'disabled') return;try {@@ -834,28 +868,42 @@ export class BotMessageRouter {}};+ const notifyGuestRejected = async (+ thread: { post: (text: string) => Promise<unknown> },+ replyLocale: BotReplyLocale,+ ): Promise<void> => {+ if (guestSettings.policy !== 'allowlist' && guestSettings.policy !== 'disabled') return;+ try {+ await thread.post(renderGuestRejected(guestSettings.policy, replyLocale));+ } catch (error) {+ log('notifyGuestRejected: failed to post rejection notice: %O', error);+ }+ };+/**- * Pairing branch of the DM gate: stranger DMed a bot in `pairing` mode.- * Issue (or recycle, when the same applicant DMed within the TTL) a- * one-time code, persist a pending entry to Redis so `/approve <code>`- * can later append the applicant to `allowFrom`, and post the code in- * the applicant's DM thread.+ * Pairing branch shared by DM and Telegram Guest policies. Issue (or+ * recycle, when the same applicant retries within the TTL) a one-time+ * code, persist a pending entry to Redis so `/approve <code>` can later+ * append the applicant to `allowFrom`, and post the code on the original+ * request surface.** Best-effort: if Redis is unwired (`'redis-unavailable'`) or the* per-bot pending cap is hit (`'capacity-exceeded'`), surface a useful* status string to the applicant rather than silently dropping them —* silent drops look broken and operators waste time debugging.*/- const triggerDmPairing = async (+ const triggerPairing = async (thread: { id: string; post: (text: string) => Promise<unknown> },author: { userId?: string; userName?: string },replyLocale: BotReplyLocale,+ scope: 'dm' | 'guest',): Promise<void> => {if (!author.userId) {log(- 'triggerDmPairing: missing author userId, cannot pair (agent=%s, platform=%s)',+ 'triggerPairing: missing author userId, cannot pair (agent=%s, platform=%s, scope=%s)',agentId,platform,+ scope,);return;}@@ -872,16 +920,25 @@ export class BotMessageRouter {});let text: string;if (result.status === 'created' || result.status === 'reused') {- text = renderDmPairing('code', replyLocale, { code: result.code });+ text =+ scope === 'guest'+ ? renderGuestPairing('code', replyLocale, { code: result.code })+ : renderDmPairing('code', replyLocale, { code: result.code });} else if (result.status === 'capacity-exceeded') {- text = renderDmPairing('capacity-exceeded', replyLocale);+ text =+ scope === 'guest'+ ? renderGuestPairing('capacity-exceeded', replyLocale)+ : renderDmPairing('capacity-exceeded', replyLocale);} else {- text = renderDmPairing('unavailable', replyLocale);+ text =+ scope === 'guest'+ ? renderGuestPairing('unavailable', replyLocale)+ : renderDmPairing('unavailable', replyLocale);}try {await thread.post(text);} catch (error) {- log('triggerDmPairing: failed to post pairing notice: %O', error);+ log('triggerPairing: failed to post pairing notice: %O', error);}};@@ -1036,18 +1093,13 @@ export class BotMessageRouter {if (operatorUserId && author.userId === operatorUserId) {return finishFeatureAccess();}- // Pairing redefines what `allowFrom` means: it's the *post-approval*- // list (managed by `/approve`), not a hard identity gate. A stranger- // DMing a pairing bot must reach the DM gate's `'pair'` branch so we- // can issue them a code — but the global allowFrom gate would- // otherwise short-circuit them out at step 1 (since they're not yet- // approved). Skip the global gate for DM threads under pairing so- // the DM gate alone governs user filtering. Other policies are- // unaffected: `open` keeps allowFrom as an extra lockdown layer,- // `allowlist` resolves to the same list either way, `disabled`- // rejects regardless.+ // Pairing redefines what `allowFrom` means: it's the post-approval+ // list. Pairing applicants must reach their scope gate so it can issue+ // a code instead of being short-circuited by the global allowlist.+ const isGuest = platform === 'telegram' && isGuestTelegramThreadId(thread.id);const isPairingDm = thread.isDM === true && dmSettings.policy === 'pairing';- if (!isPairingDm && !passesGlobalAllowlist({ author })) {+ const isPairingGuest = isGuest && guestSettings.policy === 'pairing';+ if (!isPairingDm && !isPairingGuest && !passesGlobalAllowlist({ author })) {log('%s: sender blocked by allowFrom, agent=%s, platform=%s, thread=%s, author=%s',caller,@@ -1060,6 +1112,26 @@ export class BotMessageRouter {await handleSenderRejected(thread, replyLocale);return false;}+ const guestDecision = passesGuestPolicy(thread, { author });+ if (guestDecision !== 'allow') {+ log(+ '%s: Guest gate=%s, agent=%s, platform=%s, thread=%s, author=%s, policy=%s',+ caller,+ guestDecision,+ agentId,+ platform,+ thread.id,+ author.userName ?? author.userId,+ guestSettings.policy,+ );+ await ensureRejectionVisible();+ if (guestDecision === 'pair') {+ await triggerPairing(thread, author, replyLocale, 'guest');+ } else {+ await notifyGuestRejected(thread, replyLocale);+ }+ return false;+ }if (!passesGroupPolicy(thread)) {log('%s: group blocked by policy, agent=%s, platform=%s, thread=%s, policy=%s',@@ -1088,7 +1160,7 @@ export class BotMessageRouter {dmSettings.policy,);if (dmDecision === 'pair') {- await triggerDmPairing(thread, author, replyLocale);+ await triggerPairing(thread, author, replyLocale, 'dm');} else {await notifyDmRejected(thread, replyLocale);}@@ -1656,7 +1728,7 @@ export class BotMessageRouter {* and handler. To add a new command, just append to this array.** Handlers close over `info` so they can reach services and the bot's- * own configuration (DM policy, owner identity, applicationId) without+ * own configuration (access policies, owner identity, applicationId) without* needing every command entry threaded through CommandContext.*/private buildCommands(@@ -1669,6 +1741,7 @@ export class BotMessageRouter {* the applicant's notification has to land in the applicant's DM. */client: PlatformClient;dmSettings: DmSettings;+ guestSettings: GuestSettings;operatorUserId?: string;platform: string;/** DB row id of the agent_bot_providers row for this bot — used by@@ -1683,6 +1756,7 @@ export class BotMessageRouter {applicationId,client,dmSettings,+ guestSettings,operatorUserId,platform,providerId,@@ -1825,7 +1899,7 @@ export class BotMessageRouter {ctx.authorUserName ?? ctx.authorUserId,);- if (dmSettings.policy !== 'pairing') {+ if (dmSettings.policy !== 'pairing' && guestSettings.policy !== 'pairing') {await ctx.post(renderCommandReply('cmdApproveDisabled', ctx.replyLocale));return;}@@ -1919,8 +1993,9 @@ export class BotMessageRouter {redis,});- // Notify the applicant in their own DM thread, in the locale- // they originally DMed in (owner's locale may differ).+ // Notify the applicant on the surface where they requested access,+ // in their original locale. Telegram Guest Mode can update its+ // one-shot inline response through the Guest messenger.try {const messenger = client.getMessenger(entry.threadId);await messenger.createMessage(diff --git a/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts b/apps/server/src/services/bot/__tests__/BotMessageRouter.test.tsindex 9171469da5e..6cd4a37d53f 100644--- a/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts+++ b/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts@@ -74,6 +74,9 @@ const mockOnNewMention = vi.hoisted(() => vi.fn());const mockOnSubscribedMessage = vi.hoisted(() => vi.fn());const mockOnNewMessage = vi.hoisted(() => vi.fn());const mockOnSlashCommand = vi.hoisted(() => vi.fn());+const mockWebhookHandler = vi.hoisted(() =>+ vi.fn().mockResolvedValue(new Response('OK', { status: 200 })),+);// Default state mocks for the participant tracking. Tests that// care about the multi-human transition reassign `mockGetList` to seed the// pre-existing participant list.@@ -128,7 +131,11 @@ const mockCreateAdapter = vi.hoisted(() =>const mockReconcileWebhook = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));/** Per-platform webhook handlers exposed by the mocked Chat instance (`chat.webhooks`). */const mockChatWebhooks = vi.hoisted(- () => ({}) as Record<string, (req: Request) => Promise<Response>>,+ () =>+ ({ telegram: mockWebhookHandler }) as Record<+ string,+ (req: Request, options?: any) => Promise<Response>+ >,);const mockMergeWithDefaults = vi.hoisted(() =>vi.fn((_: unknown, settings?: Record<string, unknown>) => settings ?? {}),@@ -259,6 +266,17 @@ vi.mock('../platforms', () => ({: 'open';return { policy };},+ extractGuestSettings: (settings: Record<string, unknown> | null | undefined) => {+ const rawPolicy = settings?.guestPolicy as string | undefined;+ const policy =+ rawPolicy === 'allowlist' ||+ rawPolicy === 'open' ||+ rawPolicy === 'disabled' ||+ rawPolicy === 'pairing'+ ? rawPolicy+ : 'open';+ return { policy };+ },normalizeAllowFromEntries: (raw: unknown): Array<{ id: string; name?: string }> => {if (typeof raw === 'string') {return raw@@ -410,6 +428,29 @@ vi.mock('../platforms', () => ({if (inList) return 'allow';return params.dmSettings.policy === 'pairing' ? 'pair' : 'reject';},+ shouldHandleGuest: (params: {+ authorUserId: string | undefined;+ guestSettings: { policy: 'allowlist' | 'disabled' | 'open' | 'pairing' };+ isGuest: boolean;+ operatorUserId?: string;+ userAllowlist: { ids: string[] };+ }): 'allow' | 'pair' | 'reject' => {+ if (!params.isGuest) return 'allow';+ if (params.guestSettings.policy === 'disabled') return 'reject';+ if (params.guestSettings.policy === 'open') return 'allow';+ if (!params.authorUserId) return 'reject';+ if (+ params.guestSettings.policy === 'pairing' &&+ params.operatorUserId &&+ params.authorUserId === params.operatorUserId+ ) {+ return 'allow';+ }+ const inList =+ params.userAllowlist.ids.length > 0 && params.userAllowlist.ids.includes(params.authorUserId);+ if (inList) return 'allow';+ return params.guestSettings.policy === 'pairing' ? 'pair' : 'reject';+ },shouldHandleGroup: (params: {candidateChannelIds: ReadonlyArray<string | undefined>;groupSettings: { allowFrom: string[]; policy: 'allowlist' | 'disabled' | 'open' };@@ -470,6 +511,7 @@ describe('BotMessageRouter', () => {mockProviderUpdate.mockResolvedValue(undefined);mockGetAgentRuntimeRedisClient.mockReturnValue(null);mockGetBotFeatureAccessState.mockResolvedValue({ allowed: true });+ mockChatWebhooks.telegram = mockWebhookHandler;});describe('getWebhookHandler', () => {@@ -490,6 +532,19 @@ describe('BotMessageRouter', () => {expect(typeof handler).toBe('function');});++ it('forwards webhook lifecycle options to Chat SDK', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);+ const options = { waitUntil: vi.fn() };+ const router = new BotMessageRouter();++ await router.getWebhookHandler('telegram', 'tg-bot-123')(+ new Request('https://example.com/webhook', { body: '{}', method: 'POST' }),+ options,+ );++ expect(mockWebhookHandler).toHaveBeenCalledWith(expect.any(Request), options);+ });});describe('on-demand loading', () => {@@ -1997,6 +2052,118 @@ describe('BotMessageRouter', () => {expect(thread.post.mock.calls[0][0]).toContain("doesn't respond in groups or channels");});+ it('allows open Telegram Guest Mode summons even when group policy is disabled', async () => {+ const { mention } = await loadHandlers({ groupPolicy: 'disabled' });+ const thread = {+ channelId: '-100123',+ id: 'telegram:guest:-100123',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ };++ await mention(thread, makeMentionMessage());++ expect(mockHandleMention).toHaveBeenCalledTimes(1);+ expect(thread.post).not.toHaveBeenCalled();+ });++ it('allows open Telegram Guest Mode summons that are not on the group allowlist', async () => {+ const { mention } = await loadHandlers({+ groupAllowFrom: 'channel-1',+ groupPolicy: 'allowlist',+ });+ const thread = {+ channelId: '-100999',+ id: 'telegram:guest:-100999',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ };++ await mention(thread, makeMentionMessage());++ expect(mockHandleMention).toHaveBeenCalledTimes(1);+ });++ it('blocks Telegram Guest Mode independently when Guest Policy is disabled', async () => {+ const { mention } = await loadHandlers({+ groupPolicy: 'open',+ guestPolicy: 'disabled',+ });+ const thread = {+ channelId: '-100123',+ id: 'telegram:guest:-100123',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ };++ await mention(thread, makeMentionMessage());++ expect(mockHandleMention).not.toHaveBeenCalled();+ expect(thread.post.mock.calls[0][0]).toContain('Guest Mode is disabled');+ });++ it('fails closed when Guest Policy is allowlist and Allowed Users is empty', async () => {+ const { mention } = await loadHandlers({ guestPolicy: 'allowlist' });+ const thread = {+ channelId: '-100123',+ id: 'telegram:guest:-100123',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ };++ await mention(thread, makeMentionMessage());++ expect(mockHandleMention).not.toHaveBeenCalled();+ expect(thread.post.mock.calls[0][0]).toContain("aren't authorized to use this bot");+ });++ it('allows listed users under Guest Policy allowlist', async () => {+ const { mention } = await loadHandlers({+ allowFrom: [{ id: 'alice-id' }],+ guestPolicy: 'allowlist',+ });+ const thread = {+ channelId: '-100123',+ id: 'telegram:guest:-100123',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ };++ await mention(thread, makeMentionMessage());++ expect(mockHandleMention).toHaveBeenCalledTimes(1);+ expect(thread.post).not.toHaveBeenCalled();+ });++ it('issues a pairing code to unknown Guest Mode users', async () => {+ mockCreateOrGetPairingRequest.mockResolvedValueOnce({+ code: 'PAIR123',+ status: 'created',+ });+ const { mention } = await loadHandlers({+ guestPolicy: 'pairing',+ userId: 'owner-id',+ });+ const thread = {+ channelId: '-100123',+ id: 'telegram:guest:-100123',+ isDM: false,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ };++ await mention(thread, makeMentionMessage());++ expect(mockHandleMention).not.toHaveBeenCalled();+ expect(thread.post.mock.calls[0][0]).toContain('PAIR123');+ expect(thread.post.mock.calls[0][0]).toContain('Guest Mode');+ });+it('allows @-mentions in channels listed in groupAllowFrom', async () => {const { subscribed } = await loadHandlers({groupAllowFrom: 'channel-1, channel-2',@@ -2924,6 +3091,25 @@ describe('BotMessageRouter', () => {expect(event.channel.post.mock.calls[0][0]).toMatch(/Approved Lin/i);});+ it('allows /approve when pairing is enabled only for Guest Mode', async () => {+ mockPeekPairingRequest.mockResolvedValue(PAIRING_ENTRY);+ mockProviderFindById.mockResolvedValue({+ settings: { allowFrom: [{ id: 'owner-id' }] },+ });+ mockProviderUpdate.mockResolvedValue(undefined);++ const slashApprove = await loadApproveHandler({+ dmPolicy: 'open',+ guestPolicy: 'pairing',+ });+ const event = makeApproveEvent();+ await slashApprove(event);++ expect(mockProviderUpdate).toHaveBeenCalledTimes(1);+ expect(mockDeletePairingRequest).toHaveBeenCalledTimes(1);+ expect(event.channel.post.mock.calls[0][0]).toMatch(/Approved Lin/i);+ });+it('skips the DB write when the applicant is already on allowFrom but still cleans up the code', async () => {// Read-modify-write idempotency: a second /approve for the same// user shouldn't fail just because they're already in. The codediff --git a/apps/server/src/services/bot/__tests__/formatPrompt.test.ts b/apps/server/src/services/bot/__tests__/formatPrompt.test.tsindex 8efc4fee7da..85fc2ff2b2f 100644--- a/apps/server/src/services/bot/__tests__/formatPrompt.test.ts+++ b/apps/server/src/services/bot/__tests__/formatPrompt.test.ts@@ -181,4 +181,51 @@ describe('formatPrompt', () => {expect(result).toContain('nickname="Test User"');});++ it('should prepend Telegram reply_to_message as referenced_message', () => {+ const msg = {+ ...baseMessage,+ raw: {+ reply_to_message: {+ from: { first_name: 'Dana', username: 'dana' },+ text: 'please translate this',+ },+ },+ text: '@bot 翻译',+ };+ const result = formatPrompt(msg);++ expect(result).toContain(+ '<referenced_message sender="Dana">please translate this</referenced_message>',+ );+ expect(result).toContain('@bot 翻译');+ });++ it('should use Telegram reply_to_message caption when text is empty', () => {+ expect(+ formatReferencedMessage({+ reply_to_message: { caption: 'photo caption', from: { username: 'eve' } },+ }),+ ).toBe('<referenced_message sender="eve">photo caption</referenced_message>');+ });++ it('should include both the full Telegram reply and the selected quote', () => {+ expect(+ formatReferencedMessage({+ quote: { text: 'selected fragment' },+ reply_to_message: {+ from: { first_name: 'Dana' },+ text: 'full original message',+ },+ }),+ ).toBe(+ '<referenced_message sender="Dana"><full_message>full original message</full_message>\n<selected_quote>selected fragment</selected_quote></referenced_message>',+ );+ });++ it('should preserve a selected Telegram quote when reply_to_message is omitted', () => {+ expect(formatReferencedMessage({ quote: { text: 'selected fragment' } })).toBe(+ '<referenced_message sender="unknown"><selected_quote>selected fragment</selected_quote></referenced_message>',+ );+ });});diff --git a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts b/apps/server/src/services/bot/__tests__/replyTemplate.test.tsindex d0f493bfc1e..5606ff7bf56 100644--- a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts+++ b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts@@ -10,6 +10,10 @@ import {renderErrorWithDetails,renderFinalReply,renderGroupRejected,+ renderGuestCopy,+ renderGuestPairing,+ renderGuestRejected,+ renderGuestTruncated,renderInlineError,renderLLMGenerating,renderSenderRejected,@@ -655,6 +659,21 @@ describe('replyTemplate', () => {});});+ describe('Guest Policy replies', () => {+ it('renders Guest-specific rejection copy in English and Chinese', () => {+ expect(renderGuestRejected('disabled')).toContain('Guest Mode is disabled');+ expect(renderGuestRejected('allowlist')).toContain("aren't authorized to use this bot");+ expect(renderGuestRejected('disabled', 'zh-CN')).toContain('已禁用访客模式');+ });++ it('renders Guest pairing codes and operational failures', () => {+ expect(renderGuestPairing('code', 'en-US', { code: 'PAIR123' })).toContain('PAIR123');+ expect(renderGuestPairing('code', 'en-US', { code: 'PAIR123' })).toContain('Guest Mode');+ expect(renderGuestPairing('capacity-exceeded')).toContain('too many Guest Mode');+ expect(renderGuestPairing('unavailable', 'zh-CN')).toContain('暂时不可用');+ });+ });+// ==================== renderSenderRejected ====================describe('renderSenderRejected', () => {@@ -731,6 +750,33 @@ describe('replyTemplate', () => {});});+ // ==================== renderGuestCopy ====================++ describe('renderGuestCopy', () => {+ it('returns the English Guest Mode copy by default', () => {+ expect(renderGuestCopy('guestMediaUnavailable')).toBe(+ 'This attachment can’t be delivered in Telegram Guest Mode.',+ );+ expect(renderGuestTruncated(4096)).toContain('4096');+ expect(renderGuestTruncated(1024)).toContain('1024');+ expect(renderGuestCopy('guestLinkPromptDm')).toContain('send /start');+ });++ it('returns the Chinese Guest Mode copy when locale is zh-CN', () => {+ expect(renderGuestCopy('guestMediaUnavailable', 'zh-CN')).toBe(+ '该附件无法通过 Telegram 访客模式送达。',+ );+ expect(renderGuestTruncated(4096, 'zh-CN')).toContain('4096');+ expect(renderGuestTruncated(1024, 'zh-CN')).toContain('1024');+ expect(renderGuestCopy('guestLinkPromptDm', 'zh-CN')).toContain('/start');+ expect(renderGuestCopy('guestLinkButton', 'zh-CN')).toBe('打开机器人');+ });++ it('falls back to English for locales without a Guest Mode dictionary', () => {+ expect(renderGuestCopy('guestLinkButton', 'fr-FR')).toBe('Open Bot');+ });+ });+// ==================== renderStepProgress locale ====================describe('renderStepProgress locale', () => {diff --git a/apps/server/src/services/bot/formatPrompt.ts b/apps/server/src/services/bot/formatPrompt.tsindex 12c5ddc0662..b8a12b06be8 100644--- a/apps/server/src/services/bot/formatPrompt.ts+++ b/apps/server/src/services/bot/formatPrompt.ts@@ -5,12 +5,23 @@ interface RawReferencedMessage {content?: string;}+interface TelegramReplyToMessage {+ caption?: string;+ from?: { first_name?: string; username?: string };+ text?: string;+}++interface ReferencedRaw {+ quote?: { text?: string };+ referenced_message?: RawReferencedMessage;+ reply_to_message?: TelegramReplyToMessage;+}+interface MessageLike {author: { fullName?: string; userId: string; userName?: string };raw?: {author?: { avatar?: string | null; global_name?: string | null };- referenced_message?: RawReferencedMessage;- };+ } & ReferencedRaw;text: string;}@@ -19,19 +30,38 @@ interface FormatPromptOptions {sanitizeUserInput?: (text: string) => string;}+const wrapReferencedMessage = (sender: string, content: string): string =>+ `<referenced_message sender="${sender}">${content}</referenced_message>`;+/*** Extract referenced (replied-to) message from raw payload* and format it as an XML tag for the agent prompt.*/-export const formatReferencedMessage = (- raw: { referenced_message?: RawReferencedMessage } | undefined,-): string | undefined => {- const ref = raw?.referenced_message;- if (!ref?.content) return undefined;+export const formatReferencedMessage = (raw: ReferencedRaw | undefined): string | undefined => {+ const discordRef = raw?.referenced_message;+ if (discordRef?.content) {+ const sender = discordRef.author?.global_name || discordRef.author?.username || 'unknown';+ return wrapReferencedMessage(sender, discordRef.content);+ }++ const telegramRef = raw?.reply_to_message;+ const telegramContent = telegramRef?.text || telegramRef?.caption;+ const selectedQuote = raw?.quote?.text;+ if (!telegramContent && !selectedQuote) return undefined;+ const sender = telegramRef?.from?.first_name || telegramRef?.from?.username || 'unknown';- const sender = ref.author?.global_name || ref.author?.username || 'unknown';+ if (!telegramContent) {+ return wrapReferencedMessage(sender, `<selected_quote>${selectedQuote}</selected_quote>`);+ }++ if (selectedQuote) {+ return wrapReferencedMessage(+ sender,+ `<full_message>${telegramContent}</full_message>\n<selected_quote>${selectedQuote}</selected_quote>`,+ );+ }- return `<referenced_message sender="${sender}">${ref.content}</referenced_message>`;+ return wrapReferencedMessage(sender, telegramContent);};/**diff --git a/apps/server/src/services/bot/platforms/__tests__/const.test.ts b/apps/server/src/services/bot/platforms/__tests__/const.test.tsindex daa442f8948..1afd5fde5a0 100644--- a/apps/server/src/services/bot/platforms/__tests__/const.test.ts+++ b/apps/server/src/services/bot/platforms/__tests__/const.test.ts@@ -4,6 +4,7 @@ import {allowFromField,extractDmSettings,extractGroupSettings,+ extractGuestSettings,extractUserAllowlist,extractWatchKeywordEntries,extractWatchKeywords,@@ -12,12 +13,14 @@ import {getStepReactionEmoji,makeDmPolicyField,makeGroupPolicyFields,+ makeGuestPolicyField,messageMatchesWatchKeyword,normalizeAllowFromEntries,normalizeBotReplyLocale,shouldAllowSender,shouldHandleDm,shouldHandleGroup,+ shouldHandleGuest,THINKING_REACTION_EMOJI,validateAccessSettings,WORKING_REACTION_EMOJI,@@ -134,6 +137,22 @@ describe('makeDmPolicyField', () => {});});+describe('makeGuestPolicyField', () => {+ it('produces a flat guestPolicy field with four independent access modes', () => {+ const field = makeGuestPolicyField({ policy: 'open' });++ expect(field.key).toBe('guestPolicy');+ expect(field.default).toBe('open');+ expect(field.enum).toEqual(['open', 'allowlist', 'pairing', 'disabled']);+ expect(field.enumLabels).toEqual([+ 'channel.guestPolicyOpen',+ 'channel.guestPolicyAllowlist',+ 'channel.guestPolicyPairing',+ 'channel.guestPolicyDisabled',+ ]);+ });+});+describe('allowFromField', () => {it('is an object list (id + optional name) so operators can label entries', () => {expect(allowFromField.key).toBe('allowFrom');@@ -192,6 +211,18 @@ describe('extractDmSettings', () => {});});+describe('extractGuestSettings', () => {+ it('defaults to open for backward compatibility and reads valid policies', () => {+ expect(extractGuestSettings(undefined)).toEqual({ policy: 'open' });+ expect(extractGuestSettings({ guestPolicy: 'mystery' })).toEqual({ policy: 'open' });+ expect(extractGuestSettings({ guestPolicy: 'allowlist' })).toEqual({+ policy: 'allowlist',+ });+ expect(extractGuestSettings({ guestPolicy: 'pairing' })).toEqual({ policy: 'pairing' });+ expect(extractGuestSettings({ guestPolicy: 'disabled' })).toEqual({ policy: 'disabled' });+ });+});+describe('extractUserAllowlist', () => {it('returns an empty list when allowFrom is missing or empty', () => {expect(extractUserAllowlist(undefined)).toEqual({ ids: [] });@@ -499,6 +530,93 @@ describe('shouldHandleDm', () => {});});+describe('shouldHandleGuest', () => {+ const emptyUserAllowlist = { ids: [] as string[] };+ const aliceOnly = { ids: ['alice-id'] };++ it('does not affect non-Guest traffic', () => {+ expect(+ shouldHandleGuest({+ authorUserId: undefined,+ guestSettings: { policy: 'disabled' },+ isGuest: false,+ userAllowlist: emptyUserAllowlist,+ }),+ ).toBe('allow');+ });++ it('keeps existing Guest Mode behavior under open policy', () => {+ expect(+ shouldHandleGuest({+ authorUserId: 'stranger-id',+ guestSettings: { policy: 'open' },+ isGuest: true,+ userAllowlist: emptyUserAllowlist,+ }),+ ).toBe('allow');+ });++ it('fails closed for an empty Guest allowlist and permits listed users', () => {+ expect(+ shouldHandleGuest({+ authorUserId: 'alice-id',+ guestSettings: { policy: 'allowlist' },+ isGuest: true,+ userAllowlist: emptyUserAllowlist,+ }),+ ).toBe('reject');+ expect(+ shouldHandleGuest({+ authorUserId: 'alice-id',+ guestSettings: { policy: 'allowlist' },+ isGuest: true,+ userAllowlist: aliceOnly,+ }),+ ).toBe('allow');+ });++ it('pairs strangers, permits approved users and always permits the owner', () => {+ expect(+ shouldHandleGuest({+ authorUserId: 'stranger-id',+ guestSettings: { policy: 'pairing' },+ isGuest: true,+ operatorUserId: 'owner-id',+ userAllowlist: emptyUserAllowlist,+ }),+ ).toBe('pair');+ expect(+ shouldHandleGuest({+ authorUserId: 'alice-id',+ guestSettings: { policy: 'pairing' },+ isGuest: true,+ operatorUserId: 'owner-id',+ userAllowlist: aliceOnly,+ }),+ ).toBe('allow');+ expect(+ shouldHandleGuest({+ authorUserId: 'owner-id',+ guestSettings: { policy: 'pairing' },+ isGuest: true,+ operatorUserId: 'owner-id',+ userAllowlist: emptyUserAllowlist,+ }),+ ).toBe('allow');+ });++ it('rejects every Guest summon when disabled', () => {+ expect(+ shouldHandleGuest({+ authorUserId: 'alice-id',+ guestSettings: { policy: 'disabled' },+ isGuest: true,+ userAllowlist: aliceOnly,+ }),+ ).toBe('reject');+ });+});+describe('shouldHandleGroup', () => {const open = { allowFrom: [] as string[], policy: 'open' as const };const disabled = { allowFrom: [] as string[], policy: 'disabled' as const };@@ -645,6 +763,7 @@ describe('validateAccessSettings', () => {it('passes pairing when the operator (settings.userId) is set', () => {expect(validateAccessSettings({ dmPolicy: 'pairing', userId: 'owner-id' }).valid).toBe(true);+ expect(validateAccessSettings({ guestPolicy: 'pairing', userId: 'owner-id' }).valid).toBe(true);});it('rejects pairing without a userId — owner is the approver, missing it bricks the flow', () => {@@ -653,13 +772,14 @@ describe('validateAccessSettings', () => {expect(result.errors).toEqual([{field: 'userId',- message: expect.stringContaining('Pairing policy'),+ message: expect.stringContaining('Pairing policies require'),},]);});it('treats a blank-string userId the same as missing (whitespace is not an owner)', () => {expect(validateAccessSettings({ dmPolicy: 'pairing', userId: ' ' }).valid).toBe(false);+ expect(validateAccessSettings({ guestPolicy: 'pairing', userId: ' ' }).valid).toBe(false);});it('does not require userId for allowlist or disabled — they have no approval flow', () => {diff --git a/apps/server/src/services/bot/platforms/const.ts b/apps/server/src/services/bot/platforms/const.tsindex 1488daf49e0..5a71aba1835 100644--- a/apps/server/src/services/bot/platforms/const.ts+++ b/apps/server/src/services/bot/platforms/const.ts@@ -173,6 +173,12 @@ export interface DmSettings {policy: DmPolicy;}+export type GuestPolicy = 'open' | 'allowlist' | 'pairing' | 'disabled';++export interface GuestSettings {+ policy: GuestPolicy;+}+export type GroupPolicy = 'open' | 'allowlist' | 'disabled';export interface GroupSettings {@@ -182,6 +188,12 @@ export interface GroupSettings {}const DM_POLICIES: ReadonlySet<DmPolicy> = new Set(['open', 'allowlist', 'pairing', 'disabled']);+const GUEST_POLICIES: ReadonlySet<GuestPolicy> = new Set([+ 'open',+ 'allowlist',+ 'pairing',+ 'disabled',+]);const GROUP_POLICIES: ReadonlySet<GroupPolicy> = new Set(['open', 'allowlist', 'disabled']);/**@@ -224,10 +236,42 @@ export function makeDmPolicyField(defaults: { policy: DmPolicy }): FieldSchema {};}+/**+ * Telegram Guest Policy: gate one-shot Guest Mode summons independently+ * from DMs and groups the bot has joined.+ *+ * Guest Mode is a user-scoped surface, so `allowlist` and `pairing` reuse+ * the global `allowFrom` user IDs rather than the channel-ID based+ * `groupAllowFrom` list.+ */+export function makeGuestPolicyField(defaults: { policy: GuestPolicy }): FieldSchema {+ return {+ key: 'guestPolicy',+ default: defaults.policy,+ description: 'channel.guestPolicyHint',+ enum: ['open', 'allowlist', 'pairing', 'disabled'],+ enumDescriptions: [+ 'channel.guestPolicyOpenHint',+ 'channel.guestPolicyAllowlistHint',+ 'channel.guestPolicyPairingHint',+ 'channel.guestPolicyDisabledHint',+ ],+ enumLabels: [+ 'channel.guestPolicyOpen',+ 'channel.guestPolicyAllowlist',+ 'channel.guestPolicyPairing',+ 'channel.guestPolicyDisabled',+ ],+ label: 'channel.guestPolicy',+ type: 'string',+ };+}+/*** Global user-ID allowlist. Always visible — when populated, the runtime- * applies it to **all** inbound traffic (DM and group), independently of- * `dmPolicy` and `groupPolicy` mode. Empty means "no user-level filter".+ * applies it to **all** inbound traffic (DM, group, and Telegram Guest+ * Mode), independently of the per-scope policy. Empty means "no user-level+ * filter".** Tying visibility to `dmPolicy='allowlist'` was tried earlier and rejected* because it forced operators who only wanted to scope group @mentions to@@ -607,6 +651,18 @@ export function extractDmSettings(return { policy };}+/** Read `settings.guestPolicy`. Missing or malformed input defaults to+ * `open` so existing Telegram channels keep their previous behaviour. */+export function extractGuestSettings(+ settings: Record<string, unknown> | null | undefined,+): GuestSettings {+ const rawPolicy = settings?.guestPolicy as string | undefined;+ const policy: GuestPolicy = GUEST_POLICIES.has(rawPolicy as GuestPolicy)+ ? (rawPolicy as GuestPolicy)+ : 'open';+ return { policy };+}+/*** Read the global user-ID allowlist from `settings.allowFrom`.*@@ -669,6 +725,8 @@ export function shouldAllowSender(params: {*/export type DmDecision = 'allow' | 'pair' | 'reject';+export type GuestDecision = 'allow' | 'pair' | 'reject';+/*** Gate inbound DM handling. Non-DM threads pass through unconditionally —* those are governed by `shouldHandleGroup` instead.@@ -716,6 +774,34 @@ export function shouldHandleDm(params: {return dmSettings.policy === 'pairing' ? 'pair' : 'reject';}+/**+ * Gate Telegram Guest Mode handling. Non-Guest threads pass through+ * unconditionally and continue to the normal DM / group gates.+ *+ * `allowlist` and `pairing` use the global user allowlist because Guest+ * access belongs to the summoning user, not to a chat the bot joined.+ * Pairing reuses the existing approval lifecycle and owner override.+ */+export function shouldHandleGuest(params: {+ authorUserId: string | undefined;+ guestSettings: GuestSettings;+ isGuest: boolean;+ operatorUserId?: string;+ userAllowlist: UserAllowlist;+}): GuestDecision {+ const { authorUserId, guestSettings, isGuest, operatorUserId, userAllowlist } = params;+ if (!isGuest) return 'allow';+ if (guestSettings.policy === 'disabled') return 'reject';+ if (guestSettings.policy === 'open') return 'allow';+ if (!authorUserId) return 'reject';+ if (guestSettings.policy === 'pairing' && operatorUserId && authorUserId === operatorUserId) {+ return 'allow';+ }+ const inList = userAllowlist.ids.length > 0 && userAllowlist.ids.includes(authorUserId);+ if (inList) return 'allow';+ return guestSettings.policy === 'pairing' ? 'pair' : 'reject';+}+/*** Gate inbound group/channel handling. DM threads pass through* unconditionally — those are governed by `shouldHandleDm` instead.@@ -751,12 +837,11 @@ export function shouldHandleGroup(params: {* Validate cross-platform access-policy settings at save time.** Catches misconfigurations that would silently break runtime gating- * before they hit the DB. Today this only enforces one rule:+ * before they hit the DB. Today this enforces one invariant:*- * - `dmPolicy='pairing'` requires `settings.userId` (the owner's platform- * user ID). Without it nobody can issue `/approve`, so inbound pairing- * requests would land in a permanent limbo — surface the missing field- * at save time so operators don't paint themselves into the corner.+ * - Any pairing policy requires `settings.userId` (the owner's platform user+ * ID). Without it nobody can issue `/approve`, so inbound pairing requests+ * would land in a permanent limbo.** Per-platform rules (e.g. Telegram bot tokens, Discord intents) belong* in `ClientFactory.validateSettings`; this function only encodes shared@@ -767,13 +852,14 @@ export function validateAccessSettings(): ValidationResult {const errors: Array<{ field: string; message: string }> = [];const dmSettings = extractDmSettings(settings);- if (dmSettings.policy === 'pairing') {+ const guestSettings = extractGuestSettings(settings);+ if (dmSettings.policy === 'pairing' || guestSettings.policy === 'pairing') {const operatorId = (settings?.userId as string | undefined)?.trim();if (!operatorId) {errors.push({field: 'userId',message:- "Pairing policy requires the owner's Platform User ID. Fill in 'Your Platform User ID' or pick a different DM Policy.",+ "Pairing policies require the owner's Platform User ID. Fill in 'Your Platform User ID' or pick a different access policy.",});}}diff --git a/apps/server/src/services/bot/platforms/index.ts b/apps/server/src/services/bot/platforms/index.tsindex 36cf3993d4d..6a6b3da5aec 100644--- a/apps/server/src/services/bot/platforms/index.ts+++ b/apps/server/src/services/bot/platforms/index.ts@@ -20,6 +20,7 @@ export {type DmSettings,extractDmSettings,extractGroupSettings,+ extractGuestSettings,extractUserAllowlist,extractWatchKeywordEntries,extractWatchKeywords,@@ -28,8 +29,12 @@ export {getStepReactionEmoji,type GroupPolicy,type GroupSettings,+ type GuestDecision,+ type GuestPolicy,+ type GuestSettings,makeDmPolicyField,makeGroupPolicyFields,+ makeGuestPolicyField,makeServerIdField,makeUserIdField,messageMatchesWatchKeyword,@@ -39,6 +44,7 @@ export {shouldAllowSender,shouldHandleDm,shouldHandleGroup,+ shouldHandleGuest,THINKING_REACTION_EMOJI,type UserAllowlist,validateAccessSettings,diff --git a/apps/server/src/services/bot/platforms/messageCapabilities.test.ts b/apps/server/src/services/bot/platforms/messageCapabilities.test.tsindex 2682c406431..aa91c08864a 100644--- a/apps/server/src/services/bot/platforms/messageCapabilities.test.ts+++ b/apps/server/src/services/bot/platforms/messageCapabilities.test.ts@@ -2,34 +2,20 @@ import { readFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveMessageManifest } from '@lobechat/builtin-tool-message';import { describe, expect, it } from 'vitest';-import { PLATFORM_UNSUPPORTED_MESSAGE_APIS } from './messageCapabilities';+import {+ CHANNEL_MESSAGE_APIS,+ PLATFORM_UNSUPPORTED_MESSAGE_APIS,+ resolveUnsupportedMessageApis,+ TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS,+} from './messageCapabilities';const HERE = dirname(fileURLToPath(import.meta.url));-// The `lobe-message` channel operations (bot/messenger-management APIs are-// intentionally out of scope — they're platform-independent).-const CHANNEL_APIS = [- 'sendMessage',- 'sendDirectMessage',- 'readMessages',- 'searchMessages',- 'editMessage',- 'deleteMessage',- 'reactToMessage',- 'getReactions',- 'pinMessage',- 'unpinMessage',- 'listPins',- 'getChannelInfo',- 'listChannels',- 'getMemberInfo',- 'createThread',- 'listThreads',- 'replyToThread',- 'createPoll',-];+const GUEST_THREAD_ID = 'telegram:guest:-100123:bot:bot-1:message:10';+const MEMBER_THREAD_ID = 'telegram:-100123';// platform id -> service.ts location (lark shares feishu's service)const SERVICE_DIR: Record<string, string> = {@@ -56,7 +42,7 @@ const deriveUnsupported = (serviceSource: string): string[] => {const implemented = new Set([...serviceSource.matchAll(/(\w+)\s*=\s*async\s*\(/g)].map((m) => m[1]),);- return CHANNEL_APIS.filter((api) => thrown.has(api) || !implemented.has(api)).sort();+ return CHANNEL_MESSAGE_APIS.filter((api) => thrown.has(api) || !implemented.has(api)).sort();};describe('PLATFORM_UNSUPPORTED_MESSAGE_APIS', () => {@@ -77,3 +63,47 @@ describe('PLATFORM_UNSUPPORTED_MESSAGE_APIS', () => {expect(noHistory).toEqual(['qq', 'telegram', 'wechat']);});});++describe('Telegram Guest Mode message capabilities', () => {+ it('disables every channel API and keeps bot/messenger management', () => {+ expect(TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS).toEqual([...CHANNEL_MESSAGE_APIS]);+ expect(TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS).toContain('sendMessage');+ expect(TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS).toContain('createPoll');+ expect(TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS).toContain('getMemberInfo');+ expect(TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS).not.toContain('listBots');+ expect(TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS).not.toContain('sendMessengerPush');+ });++ it('selects the guest overlay only for guest Telegram thread ids', () => {+ expect(resolveUnsupportedMessageApis('telegram', GUEST_THREAD_ID)).toEqual(+ TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS,+ );+ expect(resolveUnsupportedMessageApis('telegram', MEMBER_THREAD_ID)).toEqual(+ PLATFORM_UNSUPPORTED_MESSAGE_APIS.telegram,+ );+ expect(resolveUnsupportedMessageApis('telegram', MEMBER_THREAD_ID)).not.toContain(+ 'sendMessage',+ );+ expect(resolveUnsupportedMessageApis('wechat')).toEqual(+ PLATFORM_UNSUPPORTED_MESSAGE_APIS.wechat,+ );+ expect(resolveUnsupportedMessageApis(undefined, GUEST_THREAD_ID)).toBeUndefined();+ });++ it('hides channel tools from the Guest Mode lobe-message manifest', () => {+ const result = resolveMessageManifest({+ botPlatform: {+ id: 'telegram',+ unsupportedMessageApis: resolveUnsupportedMessageApis('telegram', GUEST_THREAD_ID),+ },+ })!;+ const names = result.api.map((api) => api.name);++ for (const api of CHANNEL_MESSAGE_APIS) {+ expect(names).not.toContain(api);+ }+ expect(names).toContain('listBots');+ expect(names).toContain('sendMessengerPush');+ expect(result.systemRole).toContain('sendMessage');+ });+});diff --git a/apps/server/src/services/bot/platforms/messageCapabilities.ts b/apps/server/src/services/bot/platforms/messageCapabilities.tsindex d7071b5a1c4..289041758fe 100644--- a/apps/server/src/services/bot/platforms/messageCapabilities.ts+++ b/apps/server/src/services/bot/platforms/messageCapabilities.ts@@ -1,5 +1,35 @@import { MessageApiName } from '@lobechat/builtin-tool-message';+import { isGuestTelegramThreadId } from './telegram/threadId';++/**+ * Channel-scoped `lobe-message` APIs (as opposed to bot/messenger management).+ * Telegram Guest Mode cannot perform any of these: the bot is not a chat+ * member and only has a single guest reply delivered by the outbound transport.+ */+export const CHANNEL_MESSAGE_APIS = [+ MessageApiName.sendMessage,+ MessageApiName.sendDirectMessage,+ MessageApiName.readMessages,+ MessageApiName.searchMessages,+ MessageApiName.editMessage,+ MessageApiName.deleteMessage,+ MessageApiName.reactToMessage,+ MessageApiName.getReactions,+ MessageApiName.pinMessage,+ MessageApiName.unpinMessage,+ MessageApiName.listPins,+ MessageApiName.getChannelInfo,+ MessageApiName.listChannels,+ MessageApiName.getMemberInfo,+ MessageApiName.createThread,+ MessageApiName.listThreads,+ MessageApiName.replyToThread,+ MessageApiName.createPoll,+] as const;++export const TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS: string[] = [...CHANNEL_MESSAGE_APIS];+/*** `lobe-message` channel APIs each platform's runtime does NOT support — either* because its service throws `PlatformUnsupportedError`, or because the optional@@ -18,6 +48,9 @@ import { MessageApiName } from '@lobechat/builtin-tool-message';* do not rely on the default. Bot/messenger-management APIs (listBots, messenger* installs, …) are intentionally excluded: they're platform-independent and must* stay available inside any IM conversation.+ *+ * Telegram Guest Mode summons are NOT this map: they overlay+ * `TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS` via `resolveUnsupportedMessageApis`.*/export const PLATFORM_UNSUPPORTED_MESSAGE_APIS: Record<string, string[]> = {// Discord implements the full surface — no entry needed, but keep it explicit.@@ -114,3 +147,19 @@ export const PLATFORM_UNSUPPORTED_MESSAGE_APIS: Record<string, string[]> = {MessageApiName.unpinMessage,],};++/**+ * Capability set for this invocation. Guest Telegram threads are not member+ * chats — regular channel tools would only fail at the Bot API — so they get+ * the guest overlay instead of `PLATFORM_UNSUPPORTED_MESSAGE_APIS.telegram`.+ */+export const resolveUnsupportedMessageApis = (+ platformId: string | undefined,+ platformThreadId?: string,+): string[] | undefined => {+ if (platformId === 'telegram' && platformThreadId && isGuestTelegramThreadId(platformThreadId)) {+ return TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS;+ }+ if (!platformId) return undefined;+ return PLATFORM_UNSUPPORTED_MESSAGE_APIS[platformId];+};diff --git a/apps/server/src/services/bot/platforms/telegram/api.test.ts b/apps/server/src/services/bot/platforms/telegram/api.test.tsindex 1be809109d8..2444e7a2dbd 100644--- a/apps/server/src/services/bot/platforms/telegram/api.test.ts+++ b/apps/server/src/services/bot/platforms/telegram/api.test.ts@@ -213,3 +213,137 @@ describe('TelegramApi HTML parse fallback', () => {expect(fetchSpy).toHaveBeenCalledTimes(2);});});++describe('TelegramApi Guest Mode', () => {+ let fetchSpy: any;++ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('answerGuestQuery posts guest_query_id + result and returns inline_message_id', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-abc' }));++ const api = new TelegramApi(BOT_TOKEN);+ const result = await api.answerGuestQuery('gq-1', { id: 'guest-reply', type: 'article' });++ expect(result).toEqual({ inline_message_id: 'inline-abc' });+ const [, init] = fetchSpy.mock.calls[0];+ expect(String(fetchSpy.mock.calls[0][0])).toContain('/answerGuestQuery');+ expect(JSON.parse((init as RequestInit).body as string)).toEqual({+ guest_query_id: 'gq-1',+ result: { id: 'guest-reply', type: 'article' },+ });+ });++ it('answerGuestArticle retries without parse_mode on HTML parse error', async () => {+ fetchSpy+ .mockResolvedValueOnce(+ telegramErrorResponse(400, "Bad Request: can't parse entities: Unclosed tag"),+ )+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-2' }));++ const api = new TelegramApi(BOT_TOKEN);+ await api.answerGuestArticle('gq-2', '<b>broken');++ expect(fetchSpy).toHaveBeenCalledTimes(2);+ const retryBody = JSON.parse((fetchSpy.mock.calls[1][1] as RequestInit).body as string);+ expect(retryBody.result.input_message_content.parse_mode).toBeUndefined();+ expect(retryBody.result.input_message_content.message_text).toBe('broken');+ });++ it('editMessageText uses inline_message_id and ignores not-modified', async () => {+ fetchSpy.mockResolvedValueOnce(+ telegramErrorResponse(400, 'Bad Request: message is not modified'),+ );++ const api = new TelegramApi(BOT_TOKEN);+ await expect(api.editMessageText('inline-1', 'same')).resolves.toBeUndefined();++ const body = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string);+ expect(body.inline_message_id).toBe('inline-1');+ expect(body.chat_id).toBeUndefined();+ });++ it('editInlineMessageMedia uses a URL and truncates captions', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({}));++ const api = new TelegramApi(BOT_TOKEN);+ await api.editInlineMessageMedia({+ caption: 'A'.repeat(2000),+ inlineMessageId: 'inline-1',+ mediaType: 'document',+ source: { url: 'https://cdn.example/file.bin' },+ });++ const body = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string);+ expect(body.inline_message_id).toBe('inline-1');+ expect(body.media.media).toBe('https://cdn.example/file.bin');+ expect(body.media.caption).toHaveLength(1024);+ expect(body.media.caption.endsWith('...')).toBe(true);+ });++ it('editInlineMessageMedia ignores not-modified', async () => {+ fetchSpy.mockResolvedValueOnce(+ telegramErrorResponse(400, 'Bad Request: message is not modified'),+ );++ const api = new TelegramApi(BOT_TOKEN);+ await expect(+ api.editInlineMessageMedia({+ caption: 'same',+ inlineMessageId: 'inline-1',+ mediaType: 'photo',+ source: { url: 'https://cdn.example/photo.png' },+ }),+ ).resolves.toBeUndefined();++ const body = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string);+ expect(body.inline_message_id).toBe('inline-1');+ expect(body.media.caption).toBe('same');+ expect(body.media.type).toBe('photo');+ });++ it('editInlineMessageCaption uses inline_message_id and ignores not-modified', async () => {+ fetchSpy.mockResolvedValueOnce(+ telegramErrorResponse(400, 'Bad Request: message is not modified'),+ );++ const api = new TelegramApi(BOT_TOKEN);+ await expect(+ api.editInlineMessageCaption({ caption: 'same', inlineMessageId: 'inline-1' }),+ ).resolves.toBeUndefined();++ const body = JSON.parse((fetchSpy.mock.calls[0][1] as RequestInit).body as string);+ expect(body.inline_message_id).toBe('inline-1');+ expect(body.caption).toBe('same');+ expect(body.parse_mode).toBe('HTML');+ expect(body.chat_id).toBeUndefined();+ });++ it('editInlineMessageCaption retries without parse_mode on HTML parse error', async () => {+ fetchSpy+ .mockResolvedValueOnce(+ telegramErrorResponse(+ 400,+ 'Bad Request: can\'t parse entities: Can\'t find end tag corresponding to start tag "b"',+ ),+ )+ .mockResolvedValueOnce(okResponse({}));++ const api = new TelegramApi(BOT_TOKEN);+ await api.editInlineMessageCaption({+ caption: '<b>broken',+ inlineMessageId: 'inline-1',+ });++ expect(fetchSpy).toHaveBeenCalledTimes(2);+ const retryBody = JSON.parse((fetchSpy.mock.calls[1][1] as RequestInit).body as string);+ expect(retryBody.parse_mode).toBeUndefined();+ expect(retryBody.caption).toBe('broken');+ });+});diff --git a/apps/server/src/services/bot/platforms/telegram/api.ts b/apps/server/src/services/bot/platforms/telegram/api.tsindex 1ba3b61e644..6376bdb8b37 100644--- a/apps/server/src/services/bot/platforms/telegram/api.ts+++ b/apps/server/src/services/bot/platforms/telegram/api.ts@@ -150,43 +150,54 @@ export class TelegramApi {return { message_id: data.result.message_id };}- async editMessageText(chatId: string | number, messageId: number, text: string): Promise<void> {- log('editMessageText: chatId=%s, messageId=%s', chatId, messageId);+ async editMessageText(chatId: string | number, messageId: number, text: string): Promise<void>;+ async editMessageText(inlineMessageId: string, text: string): Promise<void>;+ async editMessageText(+ chatIdOrInlineId: string | number,+ messageIdOrText: number | string,+ maybeText?: string,+ ): Promise<void> {+ const inline = typeof messageIdOrText === 'string';+ const text = inline ? messageIdOrText : maybeText!;+ const location = inline+ ? { inline_message_id: String(chatIdOrInlineId) }+ : { chat_id: chatIdOrInlineId, message_id: messageIdOrText };++ log('editMessageText: %O', location);if (!text.trim()) {throw new Error('Telegram API editMessageText skipped: text is empty');}try {await this.call('editMessageText', {- chat_id: chatId,- message_id: messageId,+ ...location,parse_mode: 'HTML',text: this.truncateText(text),});- } catch (error: any) {+ } catch (error) {+ const message = (error as { message?: string } | null)?.message;// Telegram returns 400 when the new content is identical to the current message — safe to ignore- if (error?.message?.includes('message is not modified')) return;+ if (message?.includes('message is not modified')) return;if (isParseEntitiesError(error)) {- log(- 'editMessageText: HTML parse failed, retrying as plain text. chatId=%s, messageId=%s',- chatId,- messageId,- );+ log('editMessageText: HTML parse failed, retrying as plain text');try {await this.call('editMessageText', {- chat_id: chatId,- message_id: messageId,+ ...location,text: this.truncateText(stripHTML(text)),});return;} catch (retryError) {if (isEditUnavailable(retryError)) {- throw new TelegramEditUnavailableError((retryError as Error).message);+ throw new TelegramEditUnavailableError(+ retryError instanceof Error ? retryError.message : String(retryError),+ );}throw retryError;}}if (isEditUnavailable(error)) {- throw new TelegramEditUnavailableError(error.message);+ throw new TelegramEditUnavailableError(+ error instanceof Error ? error.message : String(error),+ );}throw error;}@@ -660,6 +671,154 @@ export class TelegramApi {return this.sendMedia('sendAudio', 'audio', params);}+ // ==================== Guest Mode ====================++ /**+ * Reply to a Guest Mode summon. The result is posted as an inline message+ * in a chat the bot is not a member of. Returns `inline_message_id` for+ * later edits.+ */+ async answerGuestQuery(+ guestQueryId: string,+ result: Record<string, unknown>,+ ): Promise<{ inline_message_id: string }> {+ log('answerGuestQuery: id=%s, type=%s', guestQueryId, result.type);+ const data = await this.call('answerGuestQuery', {+ guest_query_id: guestQueryId,+ result,+ });+ const inlineMessageId = data.result?.inline_message_id;+ if (typeof inlineMessageId !== 'string' || !inlineMessageId) {+ throw new Error('Telegram API answerGuestQuery did not return inline_message_id');+ }+ return { inline_message_id: inlineMessageId };+ }++ /**+ * Build an article result for `answerGuestQuery`. HTML parse failures+ * retry as plain text so a malformed LLM snippet still delivers.+ */+ async answerGuestArticle(+ guestQueryId: string,+ text: string,+ extra?: { replyMarkup?: unknown; title?: string },+ ): Promise<{ inline_message_id: string }> {+ const body = text.trim() ? this.truncateText(text) : '...';+ const build = (useHtml: boolean, value: string): Record<string, unknown> => ({+ id: 'guest-reply',+ input_message_content: {+ message_text: value,+ parse_mode: useHtml ? 'HTML' : undefined,+ },+ reply_markup: extra?.replyMarkup,+ title: extra?.title ?? 'LobeHub',+ type: 'article',+ });++ try {+ return await this.answerGuestQuery(guestQueryId, build(true, body));+ } catch (error) {+ if (!isParseEntitiesError(error)) throw error;+ log('answerGuestArticle: HTML parse failed, retrying as plain text');+ return this.answerGuestQuery(guestQueryId, build(false, this.truncateText(stripHTML(body))));+ }+ }++ /**+ * Update the caption of a guest inline media message. Telegram cannot convert+ * a photo back into a text message, so later text-only Guest Mode edits go+ * here once `editMessageMedia` has succeeded.+ */+ async editInlineMessageCaption(params: {+ caption: string;+ inlineMessageId: string;+ }): Promise<void> {+ log('editInlineMessageCaption');+ const caption = this.truncateCaption(params.caption);++ const send = (useHtml: boolean): Promise<unknown> => {+ const captionForSend = useHtml ? caption : this.truncateCaption(stripHTML(caption));+ return this.call('editMessageCaption', {+ caption: captionForSend,+ inline_message_id: params.inlineMessageId,+ parse_mode: captionForSend && useHtml ? 'HTML' : undefined,+ });+ };++ try {+ await send(true);+ } catch (error) {+ const message = (error as { message?: string } | null)?.message;+ if (message?.includes('message is not modified')) return;+ if (isParseEntitiesError(error)) {+ log('editInlineMessageCaption: HTML parse failed, retrying as plain text');+ try {+ await send(false);+ return;+ } catch (retryError) {+ if (isEditUnavailable(retryError)) {+ throw new TelegramEditUnavailableError(+ retryError instanceof Error ? retryError.message : String(retryError),+ );+ }+ throw retryError;+ }+ }+ if (isEditUnavailable(error)) {+ throw new TelegramEditUnavailableError(+ error instanceof Error ? error.message : String(error),+ );+ }+ throw error;+ }+ }++ /**+ * Replace a guest inline message with media. Used so Guest Mode can still+ * deliver photos/files after the query was answered with a text placeholder.+ */+ async editInlineMessageMedia(params: {+ caption?: string;+ inlineMessageId: string;+ mediaType: 'audio' | 'document' | 'photo' | 'video';+ source: { url: string };+ }): Promise<void> {+ log('editInlineMessageMedia: type=%s', params.mediaType);+ const caption = params.caption ? this.truncateCaption(params.caption) : undefined;++ const send = (useHtml: boolean): Promise<unknown> => {+ const captionForSend =+ caption && !useHtml ? this.truncateCaption(stripHTML(caption)) : caption;+ const media: Record<string, unknown> = {+ caption: captionForSend,+ media: params.source.url,+ parse_mode: captionForSend && useHtml ? 'HTML' : undefined,+ type: params.mediaType,+ };++ return this.call('editMessageMedia', {+ inline_message_id: params.inlineMessageId,+ media,+ });+ };++ try {+ await send(true);+ } catch (error) {+ const message = (error as { message?: string } | null)?.message;+ if (message?.includes('message is not modified')) return;+ if (!caption || !isParseEntitiesError(error)) throw error;+ log('editInlineMessageMedia: caption HTML parse failed, retrying as plain text');+ try {+ await send(false);+ } catch (retryError) {+ const retryMessage = (retryError as { message?: string } | null)?.message;+ if (retryMessage?.includes('message is not modified')) return;+ throw retryError;+ }+ }+ }+/*** Telegram caption limit is 1024 characters (vs. 4096 for sendMessage).* Truncate with an ellipsis instead of letting the API reject the call.diff --git a/apps/server/src/services/bot/platforms/telegram/client.test.ts b/apps/server/src/services/bot/platforms/telegram/client.test.tsindex 7444e59b07b..44280a194d0 100644--- a/apps/server/src/services/bot/platforms/telegram/client.test.ts+++ b/apps/server/src/services/bot/platforms/telegram/client.test.ts@@ -8,11 +8,13 @@ import { resolveTelegramSecretToken } from './helpers';const { createTelegramAdapterMock } = vi.hoisted(() => ({// Typed parameter so `mock.calls[n][0]` is a config object, not `never`.- createTelegramAdapterMock: vi.fn((_config: Record<string, unknown>) => ({ name: 'telegram' })),+ createTelegramAdapterMock: vi.fn((_config: Record<string, unknown>, _sessionScope: string) => ({+ name: 'telegram',+ })),}));-vi.mock('@chat-adapter/telegram', () => ({- createTelegramAdapter: createTelegramAdapterMock,+vi.mock('./guestAdapter', () => ({+ createLobeTelegramAdapter: createTelegramAdapterMock,}));vi.mock('@/server/services/gateway/runtimeStatus', () => ({@@ -27,6 +29,7 @@ vi.mock('@/server/services/gateway/runtimeStatus', () => ({}));const BOT_TOKEN = 'test-bot-token';+const GUEST_THREAD_ID = 'telegram:guest:-100:bot:test-bot-token:message:10';const createClient = (credentials: Record<string, string> = {}) =>new TelegramClientFactory().createClient(@@ -60,19 +63,25 @@ describe('TelegramWebhookClient.createAdapter', () => {it('treats an empty-string secretToken as not configured and derives the same value', () => {createClient({ secretToken: '' }).createAdapter();- expect(createTelegramAdapterMock).toHaveBeenCalledWith({- botToken: BOT_TOKEN,- secretToken: resolveTelegramSecretToken({ botToken: BOT_TOKEN }),- });+ expect(createTelegramAdapterMock).toHaveBeenCalledWith(+ {+ botToken: BOT_TOKEN,+ secretToken: resolveTelegramSecretToken({ botToken: BOT_TOKEN }),+ },+ BOT_TOKEN,+ );});it('uses the operator-provided secretToken when configured', () => {createClient({ secretToken: 'my-webhook-secret' }).createAdapter();- expect(createTelegramAdapterMock).toHaveBeenCalledWith({- botToken: BOT_TOKEN,- secretToken: 'my-webhook-secret',- });+ expect(createTelegramAdapterMock).toHaveBeenCalledWith(+ {+ botToken: BOT_TOKEN,+ secretToken: 'my-webhook-secret',+ },+ BOT_TOKEN,+ );});});@@ -207,6 +216,30 @@ describe('TelegramWebhookClient.extractFiles', () => {]);});+ it('extracts a direct Telegram video note using raw.video_note', async () => {+ const buffer = Buffer.from('video-note-bytes');+ downloadFileSpy.mockResolvedValue(buffer);++ const client = createClient();+ const result = await client.extractFiles!(+ makeMessage({+ attachments: [{ size: 2048, type: 'video' }],+ raw: {+ video_note: {+ file_id: 'tg-video-note',+ file_size: 2048,+ length: 320,+ },+ },+ }),+ );++ expect(downloadFileSpy).toHaveBeenCalledWith('tg-video-note');+ expect((result as ExtractFilesResult)?.files).toEqual([+ { buffer, mimeType: 'video/mp4', name: 'video.mp4', size: 2048 },+ ]);+ });+it('extracts a Telegram document using file_id from raw.document', async () => {const buffer = Buffer.from('pdf-bytes');downloadFileSpy.mockResolvedValue(buffer);@@ -457,6 +490,119 @@ describe('TelegramWebhookClient.extractFiles', () => {expect(downloadFileSpy).toHaveBeenCalledTimes(1);expect(result).toBeUndefined();});++ it('downloads photo/video/document from reply_to_message when the summon has no attachments', async () => {+ const buffer = Buffer.from('quoted-photo');+ downloadFileSpy.mockResolvedValue(buffer);++ const client = createClient();+ const result = await client.extractFiles!(+ makeMessage({+ attachments: [],+ raw: {+ reply_to_message: {+ caption: 'a cat',+ photo: [+ { file_id: 'small', file_size: 100 },+ { file_id: 'quoted-large', file_size: 20_000 },+ ],+ },+ text: '@bot what is this',+ },+ }),+ );++ expect(downloadFileSpy).toHaveBeenCalledTimes(1);+ expect(downloadFileSpy).toHaveBeenCalledWith('quoted-large');+ expect((result as ExtractFilesResult)?.files).toEqual([+ { buffer, mimeType: 'image/jpeg', name: 'image.jpg', size: 20_000 },+ ]);+ });++ it('downloads a document on reply_to_message', async () => {+ const buffer = Buffer.from('quoted-pdf');+ downloadFileSpy.mockResolvedValue(buffer);++ const client = createClient();+ const result = await client.extractFiles!(+ makeMessage({+ raw: {+ reply_to_message: {+ document: {+ file_id: 'quoted-doc',+ file_name: 'notes.pdf',+ file_size: 2048,+ mime_type: 'application/pdf',+ },+ },+ },+ }),+ );++ expect(downloadFileSpy).toHaveBeenCalledWith('quoted-doc');+ expect((result as ExtractFilesResult)?.files).toEqual([+ { buffer, mimeType: 'application/pdf', name: 'notes.pdf', size: 2048 },+ ]);+ });++ it('downloads a video note on reply_to_message', async () => {+ const buffer = Buffer.from('quoted-video-note');+ downloadFileSpy.mockResolvedValue(buffer);++ const client = createClient();+ const result = await client.extractFiles!(+ makeMessage({+ raw: {+ reply_to_message: {+ video_note: {+ file_id: 'quoted-video-note',+ file_size: 4096,+ length: 320,+ },+ },+ },+ }),+ );++ expect(downloadFileSpy).toHaveBeenCalledWith('quoted-video-note');+ expect((result as ExtractFilesResult)?.files).toEqual([+ { buffer, mimeType: 'video/mp4', name: 'video.mp4', size: 4096 },+ ]);+ });++ it('keeps direct attachments and still pulls reply_to_message media', async () => {+ downloadFileSpy+ .mockResolvedValueOnce(Buffer.from('direct'))+ .mockResolvedValueOnce(Buffer.from('quoted'));++ const client = createClient();+ const result = await client.extractFiles!(+ makeMessage({+ attachments: [{ size: 10, type: 'image' }],+ raw: {+ photo: [{ file_id: 'direct-photo' }],+ reply_to_message: {+ video: {+ file_id: 'quoted-video',+ file_name: 'clip.mp4',+ file_size: 88,+ mime_type: 'video/mp4',+ },+ },+ },+ }),+ );++ expect(downloadFileSpy).toHaveBeenCalledWith('direct-photo');+ expect(downloadFileSpy).toHaveBeenCalledWith('quoted-video');+ expect((result as ExtractFilesResult)?.files).toHaveLength(2);+ expect((result as ExtractFilesResult)?.files?.[1]).toEqual({+ buffer: Buffer.from('quoted'),+ mimeType: 'video/mp4',+ name: 'clip.mp4',+ size: 88,+ });+ });});describe('TelegramWebhookClient.extractAuthorLocale', () => {@@ -476,3 +622,68 @@ describe('TelegramWebhookClient.extractAuthorLocale', () => {).toBeUndefined();});});++describe('TelegramWebhookClient thread ids', () => {+ it('extractChatId does not return "guest" for guest thread ids', () => {+ const client = createClient();+ expect(client.extractChatId('telegram:guest:-100123')).toBe('-100123');+ expect(client.extractChatId('telegram:-100123')).toBe('-100123');+ expect(client.extractChatId('telegram:guest:-100123:4')).toBe('-100123');+ });++ it('does not subscribe one-shot guest threads', () => {+ const client = createClient();+ expect(client.shouldSubscribe?.(GUEST_THREAD_ID)).toBe(false);+ expect(client.shouldSubscribe?.('telegram:-100123')).toBe(true);+ });+});++describe('TelegramWebhookClient guest messenger', () => {+ const okResponse = (body: Record<string, unknown>) =>+ new Response(JSON.stringify({ ok: true, result: body }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ });++ let fetchSpy: MockInstance<typeof fetch>;+ let resetSessions: () => void;++ beforeEach(async () => {+ const guestSession = await import('./guestSession');+ resetSessions = guestSession.resetTelegramGuestSessionsForTest;+ resetSessions();+ const client = createClient();+ await guestSession.saveTelegramGuestSession(client.applicationId, GUEST_THREAD_ID, {+ guestQueryId: 'gq-1',+ });+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ });++ afterEach(() => {+ resetSessions();+ fetchSpy.mockRestore();+ });++ it('createMessage answers the guest query instead of sendMessage', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-9' }));+ const client = createClient();+ const messenger = client.getMessenger(GUEST_THREAD_ID);++ await messenger.createMessage('thinking');+ await messenger.addReaction?.('1', '👀');++ // Guest messengers must NOT expose `triggerTyping`: its presence makes+ // AgentBridgeService treat the thread as typing-capable and skip the+ // initial placeholder post when the message gateway is enabled, leaving+ // the one-shot guest query unanswered until agent completion.+ expect(messenger.triggerTyping).toBeUndefined();++ expect(String(fetchSpy.mock.calls[0]![0])).toContain('/answerGuestQuery');+ expect(fetchSpy.mock.calls.some((call) => String(call[0]).includes('/sendMessage'))).toBe(+ false,+ );+ expect(fetchSpy.mock.calls.some((call) => String(call[0]).includes('/sendChatAction'))).toBe(+ false,+ );+ });+});diff --git a/apps/server/src/services/bot/platforms/telegram/client.ts b/apps/server/src/services/bot/platforms/telegram/client.tsindex e358bad414e..b38d01dd80d 100644--- a/apps/server/src/services/bot/platforms/telegram/client.ts+++ b/apps/server/src/services/bot/platforms/telegram/client.ts@@ -1,4 +1,3 @@-import { createTelegramAdapter } from '@chat-adapter/telegram';import type { Message } from 'chat';import debug from 'debug';@@ -22,9 +21,12 @@ import {} from '../types';import { formatUsageStats } from '../utils';import { TELEGRAM_API_BASE, TelegramApi } from './api';+import { createLobeTelegramAdapter } from './guestAdapter';+import { deliverGuestCreate, deliverGuestEdit } from './guestOutbound';import { extractBotId, resolveTelegramSecretToken, setTelegramWebhook } from './helpers';import { markdownToTelegramHTML } from './markdownToHTML';import { sendTelegramAttachments } from './sendAttachments';+import { isGuestTelegramThreadId, parseTelegramThreadId } from './threadId';const log = debug('bot-platform:telegram:bot');@@ -36,7 +38,7 @@ const log = debug('bot-platform:telegram:bot');const TELEGRAM_MAX_FILE_SIZE = 20 * 1024 * 1024; // 20 MBfunction extractChatId(platformThreadId: string): string {- return platformThreadId.split(':')[1];+ return parseTelegramThreadId(platformThreadId).chatId;}function parseTelegramMessageId(compositeId: string): number {@@ -85,6 +87,49 @@ const defaultNameForType = (type: string | undefined): string => {}};+interface TelegramMediaHint {+ mimeType?: string;+ name?: string;+ size?: number;+ type?: string;+}++/**+ * Recover photo/video/audio/document hints from a raw Telegram Message+ * payload. Used for `reply_to_message`, which Chat SDK does not copy onto+ * `message.attachments`.+ */+const mediaHintsFromTelegramPayload = (+ raw: Record<string, any> | undefined,+): TelegramMediaHint[] => {+ if (!raw) return [];+ const hints: TelegramMediaHint[] = [];++ if (Array.isArray(raw.photo) && raw.photo.length > 0) {+ const largest = raw.photo.at(-1) as { file_size?: number } | undefined;+ hints.push({ size: largest?.file_size, type: 'image' });+ }++ const pushFile = (+ payload: { file_name?: string; file_size?: number; mime_type?: string } | undefined,+ type: string,+ ) => {+ if (!payload) return;+ hints.push({+ mimeType: payload.mime_type,+ name: payload.file_name,+ size: payload.file_size,+ type,+ });+ };++ pushFile(raw.video ?? raw.video_note, 'video');+ pushFile(raw.audio ?? raw.voice, 'audio');+ pushFile(raw.document, 'file');++ return hints;+};+class TelegramWebhookClient implements PlatformClient {readonly id = 'telegram';readonly applicationId: string;@@ -184,18 +229,49 @@ class TelegramWebhookClient implements PlatformClient {createAdapter(): Record<string, any> {return {- telegram: createTelegramAdapter({- botToken: this.config.credentials.botToken,- // Always verified: the operator's secret when set, otherwise the same- // derived secret `start()` registered with Telegram. We never pass- // `allowUnverifiedWebhooks` — see `resolveTelegramSecretToken`.- secretToken: resolveTelegramSecretToken(this.config.credentials),- }),+ telegram: createLobeTelegramAdapter(+ {+ botToken: this.config.credentials.botToken,+ // Always verified: the operator's secret when set, otherwise the same+ // derived secret `start()` registered with Telegram. We never pass+ // `allowUnverifiedWebhooks` — see `resolveTelegramSecretToken`.+ secretToken: resolveTelegramSecretToken(this.config.credentials),+ },+ this.applicationId,+ ),};}getMessenger(platformThreadId: string): PlatformMessenger {const telegram = new TelegramApi(this.config.credentials.botToken);+ if (isGuestTelegramThreadId(platformThreadId)) {+ return {+ addReaction: async () => {},+ createMessage: async (content) => {+ await deliverGuestCreate(telegram, this.applicationId, platformThreadId, content);+ },+ editMessage: async (messageId, content) => {+ await deliverGuestEdit(+ telegram,+ this.applicationId,+ platformThreadId,+ messageId,+ content,+ );+ },+ // No `triggerTyping` here, on purpose. AgentBridgeService treats a+ // present `triggerTyping` as "platform can show typing" and, when the+ // message gateway is enabled, skips the initial placeholder post.+ // Guest summons are one-shot `guest_query_id`s that must be answered+ // quickly - deferring the first `createMessage` to agent completion+ // risks blowing Telegram's guest-query response window. Leaving+ // `triggerTyping` undefined forces the bridge to post the placeholder+ // immediately, which consumes the query via `answerGuestQuery`.+ removeReaction: async () => {},+ replaceReaction: async () => {},+ };+ }+const chatId = extractChatId(platformThreadId);return {addReaction: (messageId, emoji) =>@@ -286,35 +362,43 @@ class TelegramWebhookClient implements PlatformClient {* Bot API does not return `mime_type` / `file_name` for `photo` payloads,* so we must provide them.*+ * Quoted media lives on `raw.reply_to_message` (Guest Mode summons and+ * ordinary replies). Chat SDK only lists attachments on the triggering+ * message, so we recover photo/video/audio/document from that nested+ * payload the same way Discord recovers `referenced_message.attachments`.+ ** Per-attachment errors are swallowed and logged so a single failed* download doesn't drop the rest of the message's attachments.*/async extractFiles(message: Message): Promise<ExtractFilesResult | undefined> {- const attachments = (message as any).attachments as- | Array<{- mimeType?: string;- name?: string;- size?: number;- type?: string;- }>- | undefined;- if (!attachments?.length) return undefined;-+ const directAttachments = (message as any).attachments as TelegramMediaHint[] | undefined;const raw = (message as any).raw as Record<string, any> | undefined;- log('extractFiles: msgId=%s, attachments=%d', (message as any).id, attachments.length);+ const replyRaw = raw?.reply_to_message as Record<string, any> | undefined;+ const referenced = mediaHintsFromTelegramPayload(replyRaw);++ log(+ 'extractFiles: msgId=%s, direct=%d, referenced=%d',+ (message as any).id,+ directAttachments?.length ?? 0,+ referenced.length,+ );++ if (!directAttachments?.length && referenced.length === 0) return undefined;const telegram = new TelegramApi(this.config.credentials.botToken);const results: AttachmentSource[] = [];const warnings: string[] = [];- for (const att of attachments) {- const fileId = TelegramWebhookClient.resolveTelegramFileId(raw, att.type);+ const download = async (+ att: TelegramMediaHint,+ sourceRaw: Record<string, any> | undefined,+ ): Promise<void> => {+ const fileId = TelegramWebhookClient.resolveTelegramFileId(sourceRaw, att.type);if (!fileId) {log('extractFiles: no file_id for type=%s in raw payload (skipping)', att.type);- continue;+ return;}- // Check file size before attempting download (Telegram Bot API limit)if (att.size && att.size > TELEGRAM_MAX_FILE_SIZE) {const fileName = att.name ?? defaultNameForType(att.type);const sizeMB = (att.size / (1024 * 1024)).toFixed(1);@@ -327,7 +411,7 @@ class TelegramWebhookClient implements PlatformClient {warnings.push(`File "${fileName}" (${sizeMB} MB) exceeds Telegram's 20 MB download limit and could not be processed.`,);- continue;+ return;}try {@@ -347,6 +431,13 @@ class TelegramWebhookClient implements PlatformClient {} catch (error) {log('extractFiles: downloadFile failed for type=%s fileId=%s: %O', att.type, fileId, error);}+ };++ for (const att of directAttachments ?? []) {+ await download(att, raw);+ }+ for (const att of referenced) {+ await download(att, replyRaw);}if (results.length === 0 && warnings.length === 0) return undefined;@@ -372,7 +463,7 @@ class TelegramWebhookClient implements PlatformClient {return undefined;}case 'video': {- return raw.video?.file_id;+ return raw.video?.file_id ?? raw.video_note?.file_id;}case 'audio': {return raw.audio?.file_id ?? raw.voice?.file_id;@@ -398,6 +489,10 @@ class TelegramWebhookClient implements PlatformClient {parseMessageId(compositeId: string): number {return parseTelegramMessageId(compositeId);}++ shouldSubscribe(threadId: string): boolean {+ return !isGuestTelegramThreadId(threadId);+ }}export class TelegramClientFactory extends ClientFactory {diff --git a/apps/server/src/services/bot/platforms/telegram/definition.ts b/apps/server/src/services/bot/platforms/telegram/definition.tsindex f2702e4b6c0..cf3841b23aa 100644--- a/apps/server/src/services/bot/platforms/telegram/definition.ts+++ b/apps/server/src/services/bot/platforms/telegram/definition.ts@@ -15,6 +15,8 @@ export const telegram: PlatformDefinition = {setupGuideUrl: channelDocUrl('telegram'),},schema,+ // Member chats only. Guest summons overlay TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS+ // via resolveUnsupportedMessageApis — a guest bot is not a chat member.unsupportedMessageApis: PLATFORM_UNSUPPORTED_MESSAGE_APIS.telegram,clientFactory: new TelegramClientFactory(),};diff --git a/apps/server/src/services/bot/platforms/telegram/guestAdapter.test.ts b/apps/server/src/services/bot/platforms/telegram/guestAdapter.test.tsnew file mode 100644index 00000000000..667dfd0bdae--- /dev/null+++ b/apps/server/src/services/bot/platforms/telegram/guestAdapter.test.ts@@ -0,0 +1,326 @@+import { Chat } from 'chat';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { LobeTelegramAdapter } from './guestAdapter';+import {+ getTelegramGuestSession,+ resetTelegramGuestSessionsForTest,+ saveTelegramGuestSession,+} from './guestSession';+import { isGuestTelegramThreadId } from './threadId';++vi.mock('@/server/modules/AgentRuntime/redis', () => ({+ getAgentRuntimeRedisClient: () => null,+}));++const GET_ME_RESPONSE = () =>+ new Response(+ JSON.stringify({+ ok: true,+ result: { first_name: 'Bot', id: 999, is_bot: true, username: 'mybot' },+ }),+ { headers: { 'Content-Type': 'application/json' }, status: 200 },+ );++const mockGetMe = () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(GET_ME_RESPONSE());+};++const processUpdate = (adapter: LobeTelegramAdapter, update: unknown) => {+ (adapter as unknown as { processUpdate: (value: unknown) => void }).processUpdate(update);+};++const createGuestAdapter = (+ sessionScope: string,+ extra?: Partial<ConstructorParameters<typeof LobeTelegramAdapter>[0]>,+) =>+ new LobeTelegramAdapter(+ {+ botToken: '1:token',+ secretToken: 'test-secret',+ userName: 'mybot',+ ...extra,+ },+ sessionScope,+ );++const createMemoryState = () => {+ const values = new Map<string, unknown>();+ return {+ acquireLock: async (threadId: string) => ({+ expiresAt: Number.MAX_SAFE_INTEGER,+ threadId,+ token: 'token',+ }),+ appendToList: async () => {},+ connect: async () => {},+ delete: async (key: string) => {+ values.delete(key);+ },+ dequeue: async () => null,+ disconnect: async () => {},+ enqueue: async () => 1,+ extendLock: async () => true,+ forceReleaseLock: async () => {},+ get: async (key: string) => values.get(key) ?? null,+ getList: async () => [],+ isSubscribed: async () => false,+ queueDepth: async () => 0,+ releaseLock: async () => {},+ set: async (key: string, value: unknown) => {+ values.set(key, value);+ },+ setIfNotExists: async (key: string, value: unknown) => {+ if (values.has(key)) return false;+ values.set(key, value);+ return true;+ },+ subscribe: async () => {},+ unsubscribe: async () => {},+ };+};++afterEach(() => {+ resetTelegramGuestSessionsForTest();+ vi.restoreAllMocks();+});++describe('LobeTelegramAdapter Guest Mode', () => {+ it('exposes processUpdate so Guest Mode can subclass the Chat SDK adapter', () => {+ expect('processUpdate' in LobeTelegramAdapter.prototype).toBe(true);+ });++ it('treats guest thread ids as non-DM', () => {+ const adapter = createGuestAdapter('bot-1');+ expect(adapter.isDM('telegram:guest:-100123')).toBe(false);+ expect(isGuestTelegramThreadId('telegram:guest:-100123')).toBe(true);+ });++ it('keeps guest and member channels in separate namespaces', () => {+ const adapter = createGuestAdapter('bot-1');++ const firstGuest = adapter.channelIdFromThreadId('telegram:guest:-100123:bot:bot-1:message:11');+ const secondGuest = adapter.channelIdFromThreadId(+ 'telegram:guest:-100123:bot:bot-1:message:12',+ );+ expect(firstGuest).toBe('telegram:guest:-100123:bot:bot-1:message:11');+ expect(secondGuest).toBe('telegram:guest:-100123:bot:bot-1:message:12');+ expect(firstGuest).not.toBe(secondGuest);+ expect(adapter.channelIdFromThreadId('telegram:-100123')).toBe('telegram:-100123');+ });++ it('routes guest_message updates as mentions on a guest thread', async () => {+ mockGetMe();+ const adapter = createGuestAdapter('bot-1');++ const mentions: Array<{ id: string; isMention?: boolean; raw?: unknown; threadId: string }> =+ [];+ const bot = new Chat({+ adapters: { telegram: adapter },+ state: createMemoryState() as never,+ userName: 'mybot',+ });+ bot.onNewMention(async (thread, message) => {+ mentions.push({+ id: message.id,+ isMention: message.isMention,+ raw: message.raw,+ threadId: thread.id,+ });+ });+ await bot.initialize();++ processUpdate(adapter, {+ guest_message: {+ chat: { id: -100123, title: 'Room', type: 'supergroup' },+ date: 1,+ from: { first_name: 'Ada', id: 7, is_bot: false, username: 'ada' },+ guest_bot_caller_user: { first_name: 'Ada', id: 7, is_bot: false, username: 'ada' },+ guest_query_id: 'gq-42',+ message_id: 11,+ text: '@mybot hello',+ },+ update_id: 1,+ });++ await vi.waitFor(() => {+ expect(mentions.length).toBeGreaterThan(0);+ });++ expect(mentions[0]?.threadId).toBe('telegram:guest:-100123:bot:bot-1:message:11');+ expect(mentions[0]?.id).toBe('guest:bot-1:-100123:11');+ expect(mentions[0]?.isMention).toBe(true);+ expect((mentions[0]?.raw as { guest_query_id?: string } | undefined)?.guest_query_id).toBe(+ 'gq-42',+ );+ });++ it('does not dedupe the same Telegram message across guest bots', async () => {+ mockGetMe();++ const state = createMemoryState() as never;+ const mentions: Array<{ id: string; threadId: string }> = [];+ const createBot = async (sessionScope: string) => {+ const adapter = createGuestAdapter(sessionScope);+ const bot = new Chat({+ adapters: { telegram: adapter },+ state,+ userName: 'mybot',+ });+ bot.onNewMention(async (thread, message) => {+ mentions.push({ id: message.id, threadId: thread.id });+ });+ await bot.initialize();+ return adapter;+ };++ const firstAdapter = await createBot('bot-1');+ const secondAdapter = await createBot('bot-2');+ const update = {+ guest_message: {+ chat: { id: -100123, title: 'Room', type: 'supergroup' },+ date: 1,+ guest_bot_caller_user: { first_name: 'Ada', id: 7, is_bot: false },+ guest_query_id: 'gq-42',+ message_id: 11,+ text: 'hello',+ },+ update_id: 1,+ };++ processUpdate(firstAdapter, update);+ processUpdate(secondAdapter, update);++ await vi.waitFor(() => {+ expect(mentions).toHaveLength(2);+ });+ expect(mentions).toEqual(+ expect.arrayContaining([+ {+ id: 'guest:bot-1:-100123:11',+ threadId: 'telegram:guest:-100123:bot:bot-1:message:11',+ },+ {+ id: 'guest:bot-2:-100123:11',+ threadId: 'telegram:guest:-100123:bot:bot-2:message:11',+ },+ ]),+ );+ });++ it('captures the summoning user locale into the guest session', async () => {+ mockGetMe();+ const adapter = createGuestAdapter('bot-1');++ const bot = new Chat({+ adapters: { telegram: adapter },+ state: createMemoryState() as never,+ userName: 'mybot',+ });+ bot.onNewMention(async () => {});+ await bot.initialize();++ processUpdate(adapter, {+ guest_message: {+ chat: { id: -100123, title: 'Room', type: 'supergroup' },+ date: 1,+ guest_bot_caller_user: {+ first_name: 'Ada',+ id: 7,+ is_bot: false,+ language_code: 'zh-hans',+ },+ guest_query_id: 'gq-locale',+ message_id: 13,+ text: '@mybot 你好',+ },+ update_id: 3,+ });++ await vi.waitFor(async () => {+ const session = await getTelegramGuestSession(+ 'bot-1',+ 'telegram:guest:-100123:bot:bot-1:message:13',+ );+ expect(session).toMatchObject({ guestQueryId: 'gq-locale', locale: 'zh-CN' });+ });+ });++ it('preserves outbound session state when Telegram redelivers a guest update', async () => {+ mockGetMe();+ const adapter = createGuestAdapter('bot-1');+ const mentions: string[] = [];+ const bot = new Chat({+ adapters: { telegram: adapter },+ state: createMemoryState() as never,+ userName: 'mybot',+ });+ bot.onNewMention(async (_thread, message) => {+ mentions.push(message.id);+ });+ await bot.initialize();++ const update = {+ guest_message: {+ chat: { id: -100123, title: 'Room', type: 'supergroup' },+ date: 1,+ guest_bot_caller_user: { first_name: 'Ada', id: 7, is_bot: false },+ guest_query_id: 'gq-duplicate',+ message_id: 14,+ text: '@mybot hello',+ },+ update_id: 4,+ };+ const threadId = 'telegram:guest:-100123:bot:bot-1:message:14';++ processUpdate(adapter, update);+ await vi.waitFor(() => {+ expect(mentions).toHaveLength(1);+ });+ await saveTelegramGuestSession('bot-1', threadId, {+ guestQueryId: 'gq-duplicate',+ inlineMessageId: 'inline-14',+ lastText: 'photo reply',+ mediaType: 'photo',+ });++ processUpdate(adapter, update);+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(mentions).toHaveLength(1);+ await expect(getTelegramGuestSession('bot-1', threadId)).resolves.toMatchObject({+ inlineMessageId: 'inline-14',+ lastText: 'photo reply',+ mediaType: 'photo',+ });+ });++ it('rejects guest updates from users outside the adapter allowlist', async () => {+ mockGetMe();+ const adapter = createGuestAdapter('bot-1', { allowedUserIds: ['42'] });+ const mentions: string[] = [];+ const bot = new Chat({+ adapters: { telegram: adapter },+ state: createMemoryState() as never,+ userName: 'mybot',+ });+ bot.onNewMention(async (_thread, message) => {+ mentions.push(message.id);+ });+ await bot.initialize();++ processUpdate(adapter, {+ guest_message: {+ chat: { id: -100123, type: 'supergroup' },+ guest_bot_caller_user: { first_name: 'Blocked', id: 7, is_bot: false },+ guest_query_id: 'gq-blocked',+ message_id: 12,+ text: 'hello',+ },+ update_id: 2,+ });++ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(mentions).toEqual([]);+ });+});diff --git a/apps/server/src/services/bot/platforms/telegram/guestAdapter.ts b/apps/server/src/services/bot/platforms/telegram/guestAdapter.tsnew file mode 100644index 00000000000..4fd674773e0--- /dev/null+++ b/apps/server/src/services/bot/platforms/telegram/guestAdapter.ts@@ -0,0 +1,265 @@+import type { TelegramRawMessage } from '@chat-adapter/telegram';+import { TelegramAdapter } from '@chat-adapter/telegram';+import type { AdapterPostableMessage, RawMessage, WebhookOptions } from 'chat';+import { Message } from 'chat';+import debug from 'debug';++import { normalizeBotReplyLocale } from '../const';+import { TelegramApi } from './api';+import {+ deliverGuestCreate,+ deliverGuestEdit,+ messengerContentFromPostable,+} from './guestOutbound';+import { initializeTelegramGuestSession } from './guestSession';+import {+ encodeGuestTelegramThreadId,+ isGuestTelegramThreadId,+ parseTelegramThreadId,+} from './threadId';++const log = debug('lobe-server:bot:telegram-guest-adapter');++interface TelegramGuestUser {+ first_name?: string;+ id: number;+ is_bot?: boolean;+ language_code?: string;+ last_name?: string;+ username?: string;+}++interface TelegramGuestChat {+ id: number;+ title?: string;+ type: string;+ username?: string;+}++interface TelegramGuestMessage {+ [key: string]: unknown;+ caption?: string;+ chat: TelegramGuestChat;+ from?: TelegramGuestUser;+ guest_bot_caller_user?: TelegramGuestUser;+ guest_query_id?: string;+ message_id: number;+ message_thread_id?: number;+ reply_to_message?: TelegramGuestMessage;+ text?: string;+}++interface TelegramGuestUpdate {+ guest_message?: TelegramGuestMessage;+}++/**+ * Extends the Chat SDK Telegram adapter with Guest Mode:+ *+ * - inbound `guest_message` updates become mentions on `telegram:guest:{chatId}`+ * - outbound `post` / `edit` on those threads use `answerGuestQuery` /+ * `editMessageText({ inline_message_id })` instead of `sendMessage`+ *+ * Why this is a dedicated adapter wrapper instead of handling Guest Mode in+ * the regular Telegram client:+ *+ * - We still reuse the upstream `TelegramAdapter` for every normal update and+ * operation through inheritance and the `super.*` fallbacks below. Keeping+ * that path untouched lets Chat SDK continue owning ordinary Telegram+ * parsing, thread IDs, sends, typing indicators, and reactions.+ * - Guest Mode is a different Telegram transport, not just another message+ * subtype. Its inbound update is `guest_message`, while its first outbound+ * response must consume `guest_query_id` with `answerGuestQuery`. Later+ * chunks edit the returned `inline_message_id`; `sendMessage` cannot work+ * because the bot is not a member of the source chat.+ * - Guest inline messages have no normal Telegram message payload and do not+ * support chat-scoped operations such as typing or reactions. They also need+ * bot-scoped synthetic thread/message IDs plus a short-lived session that+ * bridges `guest_query_id` to `inline_message_id`.+ *+ * Isolating those protocol exceptions here avoids forking or teaching the+ * upstream adapter about LobeHub session state, while preserving one adapter+ * instance and one Chat SDK dispatch pipeline for both Telegram transports.+ */+export class LobeTelegramAdapter extends TelegramAdapter {+ private readonly sessionScope: string;++ constructor(config: ConstructorParameters<typeof TelegramAdapter>[0], sessionScope: string) {+ super(config);+ this.sessionScope = sessionScope;+ }++ protected override processUpdate(update: unknown, options?: WebhookOptions): void {+ const guestMessage = (update as TelegramGuestUpdate).guest_message;+ if (guestMessage) {+ const senderId = guestMessage.guest_bot_caller_user?.id ?? guestMessage.from?.id;+ if (+ this.allowedUserIds &&+ (senderId === undefined || !this.allowedUserIds.has(String(senderId)))+ ) {+ return;+ }+ this.handleGuestMessage(guestMessage, options);+ return;+ }+ super.processUpdate(update as never, options);+ }++ override isDM(threadId: string): boolean {+ if (isGuestTelegramThreadId(threadId)) return false;+ return super.isDM(threadId);+ }++ override decodeThreadId(threadId: string) {+ if (isGuestTelegramThreadId(threadId)) {+ const parsed = parseTelegramThreadId(threadId);+ return { chatId: parsed.chatId, messageThreadId: parsed.messageThreadId };+ }+ return super.decodeThreadId(threadId);+ }++ override channelIdFromThreadId(threadId: string): string {+ if (isGuestTelegramThreadId(threadId)) {+ const parsed = parseTelegramThreadId(threadId);+ const botScope = parsed.guestBotId ? `:bot:${parsed.guestBotId}` : '';+ return parsed.guestMessageId+ ? `telegram:guest:${parsed.chatId}${botScope}:message:${parsed.guestMessageId}`+ : `telegram:guest:${parsed.chatId}${botScope}`;+ }+ return super.channelIdFromThreadId(threadId);+ }++ override async postMessage(+ threadId: string,+ message: AdapterPostableMessage,+ _replyToMessageId?: string,+ ): Promise<RawMessage<TelegramRawMessage>> {+ if (!isGuestTelegramThreadId(threadId)) {+ return super.postMessage(threadId, message);+ }+ const api = new TelegramApi(await this.resolveBotToken());+ const sent = await deliverGuestCreate(+ api,+ this.sessionScope,+ threadId,+ messengerContentFromPostable(message),+ );+ // Guest replies are inline messages owned by the summoning user's client;+ // Telegram never returns a raw message payload for them. Only the encoded+ // inline_message_id (`sent.id`) is meaningful - consumers must not read+ // fields off `raw` for guest sends. (Inbound guest messages DO carry a+ // full raw payload; see `handleGuestMessage` / `getTelegramGuestQueryId`.)+ return { id: sent.id, raw: {} as TelegramRawMessage, threadId };+ }++ override async editMessage(+ threadId: string,+ messageId: string,+ message: AdapterPostableMessage,+ ): Promise<RawMessage<TelegramRawMessage>> {+ if (!isGuestTelegramThreadId(threadId)) {+ return super.editMessage(threadId, messageId, message);+ }+ const api = new TelegramApi(await this.resolveBotToken());+ await deliverGuestEdit(+ api,+ this.sessionScope,+ threadId,+ messageId,+ messengerContentFromPostable(message),+ );+ // Same as postMessage: inline-message edits have no raw payload, only+ // the already-encoded inline_message_id echoed back as `id`.+ return { id: messageId, raw: {} as TelegramRawMessage, threadId };+ }++ override async startTyping(threadId: string): Promise<void> {+ if (isGuestTelegramThreadId(threadId)) return;+ await super.startTyping(threadId);+ }++ override async addReaction(+ threadId: string,+ messageId: string,+ emoji: Parameters<TelegramAdapter['addReaction']>[2],+ ): Promise<void> {+ if (isGuestTelegramThreadId(threadId)) return;+ await super.addReaction(threadId, messageId, emoji);+ }++ override async removeReaction(+ threadId: string,+ messageId: string,+ emoji: Parameters<TelegramAdapter['removeReaction']>[2],+ ): Promise<void> {+ if (isGuestTelegramThreadId(threadId)) return;+ await super.removeReaction(threadId, messageId, emoji);+ }++ private handleGuestMessage(guestMessage: TelegramGuestMessage, options?: WebhookOptions): void {+ if (!this.chat) return;++ const caller = guestMessage.guest_bot_caller_user ?? guestMessage.from;+ const normalized = {+ ...guestMessage,+ from: caller,+ };+ const threadId = encodeGuestTelegramThreadId(+ String(guestMessage.chat.id),+ this.sessionScope,+ guestMessage.message_id,+ guestMessage.message_thread_id,+ );++ const guestQueryId = guestMessage.guest_query_id;+ const dispatch = async () => {+ if (guestQueryId) {+ // Remember the summoning user's Telegram locale so Guest Mode+ // notices (truncation / attachment fallbacks) render in their+ // language on the first reply and every later edit.+ await initializeTelegramGuestSession(this.sessionScope, threadId, {+ guestQueryId,+ locale: normalizeBotReplyLocale(caller?.language_code),+ });+ }+ if (!this.chat) return;+ const parsed = this.parseTelegramMessage(normalized as never, threadId);+ const message = forceGuestMention(parsed as Message, this.sessionScope);+ this.chat.processMessage(this, threadId, message, options);+ };++ const task = dispatch().catch((error) => {+ log('failed to dispatch guest message: %O', error);+ });+ options?.waitUntil?.(task);+ }+}++const forceGuestMention = (parsed: Message, sessionScope: string): Message => {+ try {+ return new Message({+ attachments: parsed.attachments,+ author: parsed.author,+ formatted: parsed.formatted,+ id: `guest:${sessionScope}:${parsed.id}`,+ isMention: true,+ links: parsed.links,+ metadata: parsed.metadata,+ raw: parsed.raw,+ replyTo: parsed.replyTo,+ text: parsed.text,+ threadId: parsed.threadId,+ });+ } catch (error) {+ log('failed to clone guest message with isMention, mutating: %O', error);+ const mutable = parsed as { id: string; isMention: boolean };+ mutable.id = `guest:${sessionScope}:${parsed.id}`;+ mutable.isMention = true;+ return parsed;+ }+};++export const createLobeTelegramAdapter = (+ config: ConstructorParameters<typeof TelegramAdapter>[0],+ sessionScope: string,+): LobeTelegramAdapter => new LobeTelegramAdapter(config, sessionScope);diff --git a/apps/server/src/services/bot/platforms/telegram/guestOutbound.test.ts b/apps/server/src/services/bot/platforms/telegram/guestOutbound.test.tsnew file mode 100644index 00000000000..b79ad741bb8--- /dev/null+++ b/apps/server/src/services/bot/platforms/telegram/guestOutbound.test.ts@@ -0,0 +1,504 @@+import type { MockInstance } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TelegramApi } from './api';+import { deliverGuestCreate, deliverGuestEdit } from './guestOutbound';+import {+ getTelegramGuestSession,+ resetTelegramGuestSessionsForTest,+ saveTelegramGuestSession,+} from './guestSession';++vi.mock('@/server/modules/AgentRuntime/redis', () => ({+ getAgentRuntimeRedisClient: () => null,+}));++const BOT_TOKEN = 'test-bot-token';+const SESSION_SCOPE = 'bot-1';+const THREAD_ID = 'telegram:guest:-100:message:10';++const okResponse = (body: Record<string, unknown>) =>+ new Response(JSON.stringify({ ok: true, result: body }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ });++describe('deliverGuestCreate / deliverGuestEdit', () => {+ let fetchSpy: MockInstance<typeof fetch>;++ beforeEach(() => {+ fetchSpy = vi.spyOn(globalThis, 'fetch');+ resetTelegramGuestSessionsForTest();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ resetTelegramGuestSessionsForTest();+ });++ it('answers the guest query on the first createMessage', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-1' }));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ const sent = await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, 'hello');++ expect(sent.id).toBe('guest-inline:inline-1');+ expect(String(fetchSpy.mock.calls[0]![0])).toContain('/answerGuestQuery');+ const body = JSON.parse((fetchSpy.mock.calls[0]![1] as RequestInit).body as string);+ expect(body.guest_query_id).toBe('gq-1');+ expect(body.result.type).toBe('article');+ });++ it('edits the inline message on a later editMessage', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-1',+ });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestEdit(api, SESSION_SCOPE, THREAD_ID, 'guest-inline:inline-1', 'final');++ expect(String(fetchSpy.mock.calls[0]![0])).toContain('/editMessageText');+ const body = JSON.parse((fetchSpy.mock.calls[0]![1] as RequestInit).body as string);+ expect(body.inline_message_id).toBe('inline-1');+ expect(body.text).toBe('final');+ expect(body.chat_id).toBeUndefined();+ });++ it('answers with an article before replacing it with URL-backed media', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-photo' }))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/pic.png',+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: 'caption',+ });++ const answerBody = JSON.parse((fetchSpy.mock.calls[0]![1] as RequestInit).body as string);+ expect(answerBody.result.type).toBe('article');++ const editBody = JSON.parse((fetchSpy.mock.calls[1]![1] as RequestInit).body as string);+ expect(String(fetchSpy.mock.calls[1]![0])).toContain('/editMessageMedia');+ expect(editBody.inline_message_id).toBe('inline-photo');+ expect(editBody.media).toMatchObject({+ caption: 'caption',+ media: 'https://cdn.example/pic.png',+ type: 'photo',+ });+ });++ it('updates the caption after a guest reply has been converted to a photo', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-photo' }))+ .mockResolvedValueOnce(okResponse({}))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, 'hello');+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/pic.png',+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: 'caption',+ });+ await deliverGuestEdit(api, SESSION_SCOPE, THREAD_ID, 'guest-inline:inline-photo', 'final');++ expect(String(fetchSpy.mock.calls[1]![0])).toContain('/editMessageMedia');+ expect(String(fetchSpy.mock.calls[2]![0])).toContain('/editMessageCaption');+ expect(String(fetchSpy.mock.calls[2]![0])).not.toContain('/editMessageText');+ const captionBody = JSON.parse((fetchSpy.mock.calls[2]![1] as RequestInit).body as string);+ expect(captionBody.inline_message_id).toBe('inline-photo');+ expect(captionBody.caption).toBe('final');+ expect(captionBody.chat_id).toBeUndefined();+ });++ it('updates the caption when the first guest reply was already converted to a photo', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-photo' }))+ .mockResolvedValueOnce(okResponse({}))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/pic.png',+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: 'caption',+ });+ await deliverGuestEdit(api, SESSION_SCOPE, THREAD_ID, 'guest-inline:inline-photo', 'updated');++ expect(String(fetchSpy.mock.calls[2]![0])).toContain('/editMessageCaption');+ const captionBody = JSON.parse((fetchSpy.mock.calls[2]![1] as RequestInit).body as string);+ expect(captionBody.caption).toBe('updated');+ });++ it('keeps later caption chunks visible after a photo reply hits the 1024-character limit', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-photo' }))+ .mockResolvedValueOnce(okResponse({}))+ .mockResolvedValueOnce(okResponse({}))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/pic.png',+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: 'caption',+ });+ await deliverGuestEdit(+ api,+ SESSION_SCOPE,+ THREAD_ID,+ 'guest-inline:inline-photo',+ 'A'.repeat(1500),+ );+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, 'VISIBLE');++ const longCaption = JSON.parse((fetchSpy.mock.calls[2]![1] as RequestInit).body as string);+ expect(String(fetchSpy.mock.calls[2]![0])).toContain('/editMessageCaption');+ expect(longCaption.caption).toHaveLength(1024);+ expect(longCaption.caption).toContain('1024-character');+ expect(longCaption.caption).not.toContain('4096-character');++ const appendCaption = JSON.parse((fetchSpy.mock.calls[3]![1] as RequestInit).body as string);+ expect(String(fetchSpy.mock.calls[3]![0])).toContain('/editMessageCaption');+ expect(appendCaption.caption).toContain('VISIBLE');+ expect(appendCaption.caption).toContain(+ 'Response truncated because Telegram Guest Mode supports one 1024-character reply.',+ );+ expect(appendCaption.caption.length).toBeLessThanOrEqual(1024);++ const session = await getTelegramGuestSession(SESSION_SCOPE, THREAD_ID);+ expect(session?.lastText).toContain('VISIBLE');+ expect(session?.lastText?.length).toBeLessThanOrEqual(1024);+ expect(session?.truncated).toBe(true);+ });++ it('keeps the truncation notice when a later caption chunk also replaces the photo', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-photo' }))+ .mockResolvedValueOnce(okResponse({}))+ .mockResolvedValueOnce(okResponse({}))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/first.png',+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: 'caption',+ });+ await deliverGuestEdit(+ api,+ SESSION_SCOPE,+ THREAD_ID,+ 'guest-inline:inline-photo',+ 'A'.repeat(1500),+ );+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/second.png',+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: 'VISIBLE',+ });++ expect(String(fetchSpy.mock.calls[3]![0])).toContain('/editMessageMedia');+ const mediaBody = JSON.parse((fetchSpy.mock.calls[3]![1] as RequestInit).body as string);+ expect(mediaBody.media.caption).toContain('VISIBLE');+ expect(mediaBody.media.caption).toContain(+ 'Response truncated because Telegram Guest Mode supports one 1024-character reply.',+ );+ expect(mediaBody.media.caption).toHaveLength(1024);++ await expect(getTelegramGuestSession(SESSION_SCOPE, THREAD_ID)).resolves.toMatchObject({+ mediaType: 'photo',+ truncated: true,+ });+ });++ it('does not count a successfully delivered image fallback link against caption budget', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-photo',+ mediaType: 'photo',+ });+ const caption = 'A'.repeat(1000);++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestEdit(api, SESSION_SCOPE, THREAD_ID, 'guest-inline:inline-photo', {+ attachments: [+ {+ fetchUrl: `https://cdn.example/${'long-path-'.repeat(20)}photo.png`,+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: caption,+ });++ const mediaBody = JSON.parse((fetchSpy.mock.calls[0]![1] as RequestInit).body as string);+ expect(String(fetchSpy.mock.calls[0]![0])).toContain('/editMessageMedia');+ expect(mediaBody.media.caption).toBe(caption);+ await expect(getTelegramGuestSession(SESSION_SCOPE, THREAD_ID)).resolves.toMatchObject({+ lastText: caption,+ mediaType: 'photo',+ truncated: false,+ });+ });++ it('clears persisted truncation state when an edit replaces the body with shorter text', async () => {+ fetchSpy.mockImplementation(async () => okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-photo',+ mediaType: 'photo',+ });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestEdit(+ api,+ SESSION_SCOPE,+ THREAD_ID,+ 'guest-inline:inline-photo',+ 'A'.repeat(1500),+ );+ await deliverGuestEdit(+ api,+ SESSION_SCOPE,+ THREAD_ID,+ 'guest-inline:inline-photo',+ 'complete replacement',+ );++ const replacementBody = JSON.parse((fetchSpy.mock.calls[1]![1] as RequestInit).body as string);+ expect(replacementBody.caption).toBe('complete replacement');+ expect(replacementBody.caption).not.toContain('Response truncated');+ await expect(getTelegramGuestSession(SESSION_SCOPE, THREAD_ID)).resolves.toMatchObject({+ lastText: 'complete replacement',+ truncated: false,+ });+ });++ it('replaces an existing guest photo with a later image instead of editing text', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-photo' }))+ .mockResolvedValueOnce(okResponse({}))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/first.png',+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: 'first',+ });+ await deliverGuestEdit(api, SESSION_SCOPE, THREAD_ID, 'guest-inline:inline-photo', {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/second.png',+ mimeType: 'image/png',+ type: 'image',+ },+ ],+ content: 'second',+ });++ expect(String(fetchSpy.mock.calls[2]![0])).toContain('/editMessageMedia');+ const mediaBody = JSON.parse((fetchSpy.mock.calls[2]![1] as RequestInit).body as string);+ expect(mediaBody.media).toMatchObject({+ caption: 'second',+ media: 'https://cdn.example/second.png',+ type: 'photo',+ });+ });++ it('keeps the article text when an attachment has only base64 data', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-data' }));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [{ data: 'aGVsbG8=', mimeType: 'image/png', type: 'image' }],+ content: 'text survives',+ });++ expect(fetchSpy).toHaveBeenCalledTimes(1);+ const answerBody = JSON.parse((fetchSpy.mock.calls[0]![1] as RequestInit).body as string);+ expect(answerBody.result.type).toBe('article');+ expect(answerBody.result.input_message_content.message_text).toContain('text survives');+ expect(answerBody.result.input_message_content.message_text).toContain(+ 'This attachment can’t be delivered in Telegram Guest Mode.',+ );+ });++ it('keeps non-image URL attachments as links instead of attempting inline media edits', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-file' }));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://app.example/f/file-id',+ name: 'report.pdf',+ type: 'file',+ },+ ],+ content: 'Download the report',+ });++ expect(fetchSpy).toHaveBeenCalledTimes(1);+ const answerBody = JSON.parse((fetchSpy.mock.calls[0]![1] as RequestInit).body as string);+ expect(answerBody.result.input_message_content.message_text).toContain('Download the report');+ expect(answerBody.result.input_message_content.message_text).toContain(+ '<a href="https://app.example/f/file-id">report.pdf</a>',+ );+ });++ it('represents every attachment in the single guest reply', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-many' }));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ { fetchUrl: 'https://cdn.example/first.png', name: 'first.png', type: 'image' },+ { fetchUrl: 'https://cdn.example/second.png', name: 'second.png', type: 'image' },+ ],+ content: 'Generated files',+ });++ expect(fetchSpy).toHaveBeenCalledTimes(1);+ const answerBody = JSON.parse((fetchSpy.mock.calls[0]![1] as RequestInit).body as string);+ const messageText = answerBody.result.input_message_content.message_text;+ expect(messageText).toContain('<a href="https://cdn.example/first.png">first.png</a>');+ expect(messageText).toContain('<a href="https://cdn.example/second.png">second.png</a>');+ });++ it('shows an explicit notice when later chunks exceed the single-reply limit', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-long' }))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, 'A'.repeat(4000));+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, 'B'.repeat(4000));++ const editBody = JSON.parse((fetchSpy.mock.calls[1]![1] as RequestInit).body as string);+ expect(editBody.text).toHaveLength(4096);+ expect(editBody.text).toContain(+ 'Response truncated because Telegram Guest Mode supports one 4096-character reply.',+ );+ });++ it('keeps accumulated text when the final chunk carries an image', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-image-long' }))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, { guestQueryId: 'gq-1' });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, 'A'.repeat(4000));+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [+ {+ fetchUrl: 'https://cdn.example/final.png',+ name: 'final.png',+ type: 'image',+ },+ ],+ content: 'B'.repeat(1024),+ });++ expect(String(fetchSpy.mock.calls[1]![0])).toContain('/editMessageText');+ const editBody = JSON.parse((fetchSpy.mock.calls[1]![1] as RequestInit).body as string);+ expect(editBody.text).toContain('A'.repeat(100));+ expect(editBody.text).toContain('<a href="https://cdn.example/final.png">final.png</a>');+ expect(editBody.text).toContain('Response truncated');+ });++ it('localizes guest notices to the summoner locale stored on the session', async () => {+ fetchSpy.mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-zh' }));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, {+ guestQueryId: 'gq-1',+ locale: 'zh-CN',+ });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, {+ attachments: [{ data: 'aGVsbG8=', mimeType: 'image/png', type: 'image' }],+ content: 'text survives',+ });++ const answerBody = JSON.parse((fetchSpy.mock.calls[0]![1] as RequestInit).body as string);+ expect(answerBody.result.input_message_content.message_text).toContain('text survives');+ expect(answerBody.result.input_message_content.message_text).toContain(+ '该附件无法通过 Telegram 访客模式送达。',+ );+ expect(answerBody.result.input_message_content.message_text).not.toContain(+ 'This attachment can’t be delivered',+ );+ });++ it('keeps localizing later edits from the persisted session locale', async () => {+ fetchSpy+ .mockResolvedValueOnce(okResponse({ inline_message_id: 'inline-zh-long' }))+ .mockResolvedValueOnce(okResponse({}));+ await saveTelegramGuestSession(SESSION_SCOPE, THREAD_ID, {+ guestQueryId: 'gq-1',+ locale: 'zh-CN',+ });++ const api = new TelegramApi(BOT_TOKEN);+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, 'A'.repeat(4000));+ await deliverGuestCreate(api, SESSION_SCOPE, THREAD_ID, 'B'.repeat(4000));++ const editBody = JSON.parse((fetchSpy.mock.calls[1]![1] as RequestInit).body as string);+ expect(editBody.text).toHaveLength(4096);+ expect(editBody.text).toContain('回复已被截断:Telegram 访客模式仅支持一条 4096 字符的回复。');+ expect(editBody.text).not.toContain('Response truncated');+ });+});diff --git a/apps/server/src/services/bot/platforms/telegram/guestOutbound.ts b/apps/server/src/services/bot/platforms/telegram/guestOutbound.tsnew file mode 100644index 00000000000..f9955a0e813--- /dev/null+++ b/apps/server/src/services/bot/platforms/telegram/guestOutbound.ts@@ -0,0 +1,343 @@+import debug from 'debug';++import { renderGuestCopy, renderGuestTruncated } from '../../replyTemplate';+import type { BotReplyLocale } from '../const';+import type { BotMessageAttachment, MessengerContent } from '../types';+import { messengerContentText } from '../types';+import type { TelegramApi } from './api';+import {+ getTelegramGuestSession,+ saveTelegramGuestSession,+ type TelegramGuestSession,+} from './guestSession';+import { markdownToTelegramHTML } from './markdownToHTML';+import { decodeGuestInlineMessageId, encodeGuestInlineMessageId } from './threadId';++const log = debug('lobe-server:bot:telegram-guest-outbound');++const TELEGRAM_CAPTION_LIMIT = 1024;+const TELEGRAM_TEXT_LIMIT = 4096;++const escapeTelegramHTML = (value: string): string =>+ value+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"');++const attachmentFallbackText = (+ attachment: BotMessageAttachment,+ index: number,+ lng?: BotReplyLocale,+): string => {+ const label = escapeTelegramHTML(attachment.name?.trim() || `Attachment ${index + 1}`);+ if (!attachment.fetchUrl) {+ return `${label}: ${renderGuestCopy('guestMediaUnavailable', lng)}`;+ }+ return `<a href="${escapeTelegramHTML(attachment.fetchUrl)}">${label}</a>`;+};++const guestBodyLimit = (mediaType: TelegramGuestSession['mediaType']): number =>+ mediaType === 'photo' ? TELEGRAM_CAPTION_LIMIT : TELEGRAM_TEXT_LIMIT;++interface GuestTextOptions {+ attachments?: BotMessageAttachment[];+ limit?: number;+ locale?: BotReplyLocale;+ retainedTailLength?: number;+ retainTruncationNotice?: boolean;+}++interface PreparedGuestText {+ displayText: string;+ storedText: string;+ truncated: boolean;+}++const prepareGuestText = (+ text: string,+ {+ attachments,+ limit = TELEGRAM_TEXT_LIMIT,+ locale,+ retainedTailLength = 0,+ retainTruncationNotice = false,+ }: GuestTextOptions = {},+): PreparedGuestText => {+ const fallbackLines =+ attachments?.map((att, index) => attachmentFallbackText(att, index, locale)) ?? [];+ const fallbackText = fallbackLines.join('\n');+ let combinedText = fallbackText || text;+ if (text.trim() && fallbackText) {+ combinedText = `${text}\n\n${fallbackText}`;+ }+ if (combinedText.length <= limit && !retainTruncationNotice) {+ return { displayText: combinedText, storedText: text, truncated: false };+ }++ const truncatedNotice = `\n\n${renderGuestTruncated(limit, locale)}`;+ const overflowNotice = renderGuestCopy('guestAttachmentOverflow', locale);+ const fallbackBudget = limit - truncatedNotice.length - overflowNotice.length;+ const includedFallbacks: string[] = [];+ for (const line of fallbackLines) {+ const candidate = [...includedFallbacks, line].join('\n');+ if (candidate.length > fallbackBudget) break;+ includedFallbacks.push(line);+ }+ const omittedAttachments = includedFallbacks.length < fallbackLines.length;+ const fallbackSection = [+ ...includedFallbacks,+ ...(omittedAttachments ? [overflowNotice] : []),+ ].join('\n');+ const suffix = fallbackSection ? `${truncatedNotice}\n\n${fallbackSection}` : truncatedNotice;+ const textBudget = Math.max(0, limit - suffix.length);+ const tailLength = Math.min(retainedTailLength, textBudget);+ const storedText =+ tailLength > 0 && text.length > textBudget+ ? `${text.slice(0, textBudget - tailLength)}${text.slice(-tailLength)}`+ : text.slice(0, textBudget);+ return {+ displayText: `${storedText}${suffix}`,+ storedText,+ truncated: true,+ };+};++const canApplyMedia = (+ attachments: BotMessageAttachment[] | undefined,+ caption: string,+): attachments is [BotMessageAttachment & { fetchUrl: string }] =>+ attachments?.length === 1 &&+ attachments[0]?.type === 'image' &&+ Boolean(attachments[0].fetchUrl) &&+ caption.length <= TELEGRAM_CAPTION_LIMIT;++const applyMedia = async (+ api: TelegramApi,+ inlineMessageId: string,+ attachment: BotMessageAttachment & { fetchUrl: string },+ caption: string,+): Promise<boolean> => {+ try {+ await api.editInlineMessageMedia({+ caption: caption.trim() ? caption : undefined,+ inlineMessageId,+ mediaType: 'photo',+ source: { url: attachment.fetchUrl },+ });+ return true;+ } catch (error) {+ log('editInlineMessageMedia failed: %O', error);+ return false;+ }+};++const tryApplyMedia = async (+ api: TelegramApi,+ inlineMessageId: string,+ attachments: BotMessageAttachment[] | undefined,+ text: string,+ options: Omit<GuestTextOptions, 'attachments' | 'limit'>,+): Promise<PreparedGuestText | undefined> => {+ if (!canApplyMedia(attachments, text)) return undefined;++ const prepared = prepareGuestText(text, { ...options, limit: TELEGRAM_CAPTION_LIMIT });+ const delivered = await applyMedia(api, inlineMessageId, attachments[0], prepared.displayText);+ return delivered ? prepared : undefined;+};++/**+ * Telegram distinguishes text vs media edits. After `editMessageMedia` the+ * inline message is a photo, so later body updates must use caption edits.+ * Guest Mode keeps the photo rather than trying to convert it back to text.+ */+const editGuestMessageBody = async (+ api: TelegramApi,+ inlineMessageId: string,+ text: string,+ mediaType: TelegramGuestSession['mediaType'],+): Promise<void> => {+ if (mediaType === 'photo') {+ await api.editInlineMessageCaption({ caption: text, inlineMessageId });+ return;+ }+ await api.editMessageText(inlineMessageId, text);+};++export const deliverGuestCreate = async (+ api: TelegramApi,+ sessionScope: string,+ threadId: string,+ content: MessengerContent,+): Promise<{ id: string }> => {+ const text = messengerContentText(content);+ const attachments = typeof content === 'string' ? undefined : content.attachments;+ const session = await getTelegramGuestSession(sessionScope, threadId);+ if (!session || (!session.guestQueryId && !session.inlineMessageId)) {+ throw new Error(`Telegram guest reply has no session for thread ${threadId}`);+ }++ if (!session.inlineMessageId) {+ return answerGuestQuery(api, sessionScope, threadId, session, text, attachments);+ }++ return editExistingGuest(api, sessionScope, threadId, session, text, attachments, {+ replaceText: false,+ });+};++export const deliverGuestEdit = async (+ api: TelegramApi,+ sessionScope: string,+ threadId: string,+ messageId: string,+ content: MessengerContent,+): Promise<void> => {+ const text = messengerContentText(content);+ const attachments = typeof content === 'string' ? undefined : content.attachments;+ const session = (await getTelegramGuestSession(sessionScope, threadId)) ?? {+ guestQueryId: '',+ };+ const inlineFromId = decodeGuestInlineMessageId(messageId) ?? session.inlineMessageId;+ if (!inlineFromId) {+ throw new Error(`Telegram guest edit has no inline_message_id for thread ${threadId}`);+ }+ await editExistingGuest(+ api,+ sessionScope,+ threadId,+ { ...session, inlineMessageId: inlineFromId },+ text,+ attachments,+ { replaceText: true },+ );+};++const answerGuestQuery = async (+ api: TelegramApi,+ sessionScope: string,+ threadId: string,+ session: TelegramGuestSession,+ text: string,+ attachments: BotMessageAttachment[] | undefined,+): Promise<{ id: string }> => {+ const fallbackPrepared = prepareGuestText(text, {+ attachments,+ limit: guestBodyLimit(session.mediaType),+ locale: session.locale,+ });+ const { inline_message_id: inlineMessageId } = await api.answerGuestArticle(+ session.guestQueryId,+ fallbackPrepared.displayText,+ );+ const mediaPrepared = await tryApplyMedia(api, inlineMessageId, attachments, text, {+ locale: session.locale,+ });+ const persistedPrepared = mediaPrepared ?? fallbackPrepared;++ await saveTelegramGuestSession(sessionScope, threadId, {+ ...session,+ inlineMessageId,+ lastText: persistedPrepared.storedText,+ mediaType: mediaPrepared ? 'photo' : session.mediaType,+ truncated: persistedPrepared.truncated,+ });+ return { id: encodeGuestInlineMessageId(inlineMessageId) };+};++const editExistingGuest = async (+ api: TelegramApi,+ sessionScope: string,+ threadId: string,+ session: TelegramGuestSession,+ text: string,+ attachments: BotMessageAttachment[] | undefined,+ options: { replaceText: boolean },+): Promise<{ id: string }> => {+ const inlineMessageId = session.inlineMessageId!;+ let nextText = text;+ let appendedTextLength = 0;+ if (+ !options.replaceText &&+ session.lastText?.trim() &&+ text.trim() &&+ session.lastText !== text+ ) {+ const separator = '\n\n';+ nextText = `${session.lastText}${separator}${text}`;+ appendedTextLength = separator.length + text.length;+ }+ const retainTruncationNotice = !options.replaceText && session.truncated;+ const retainedTailLength = session.truncated ? appendedTextLength : 0;+ const fallbackPrepared = prepareGuestText(nextText, {+ attachments,+ limit: guestBodyLimit(session.mediaType),+ locale: session.locale,+ retainedTailLength,+ retainTruncationNotice,+ });+ let mediaType = session.mediaType;+ let persistedPrepared = fallbackPrepared;++ const mediaPrepared = await tryApplyMedia(api, inlineMessageId, attachments, nextText, {+ locale: session.locale,+ retainedTailLength,+ retainTruncationNotice,+ });+ if (mediaPrepared) {+ mediaType = 'photo';+ persistedPrepared = mediaPrepared;+ } else if (fallbackPrepared.displayText.trim()) {+ await editGuestMessageBody(api, inlineMessageId, fallbackPrepared.displayText, mediaType);+ }++ await saveTelegramGuestSession(sessionScope, threadId, {+ ...session,+ inlineMessageId,+ lastText: persistedPrepared.storedText,+ mediaType,+ truncated: persistedPrepared.truncated,+ });+ return { id: encodeGuestInlineMessageId(inlineMessageId) };+};++/**+ * Convert a Chat SDK postable payload into the HTML + attachment shape+ * Guest Mode outbound expects. Callbacks already HTML-format via+ * `formatMarkdown`; local `thread.post({ markdown })` still needs conversion.+ */+export const messengerContentFromPostable = (message: unknown): MessengerContent => {+ if (typeof message === 'string') {+ return markdownToTelegramHTML(message);+ }+ if (!message || typeof message !== 'object') return '';+ const record = message as {+ attachments?: Array<{+ data?: Buffer;+ mimeType?: string;+ name?: string;+ size?: number;+ type?: BotMessageAttachment['type'];+ url?: string;+ }>;+ markdown?: string;+ text?: string;+ };+ const rawText = record.markdown ?? record.text ?? '';+ const content = record.markdown ? markdownToTelegramHTML(rawText) : rawText;+ const attachments = record.attachments?.flatMap((att) => {+ if (!att.type) return [];+ return [+ {+ data: att.data?.toString('base64'),+ fetchUrl: att.url,+ mimeType: att.mimeType,+ name: att.name,+ size: att.size,+ type: att.type,+ } satisfies BotMessageAttachment,+ ];+ });+ if (!attachments?.length) return content;+ return { attachments, content };+};diff --git a/apps/server/src/services/bot/platforms/telegram/guestSession.test.ts b/apps/server/src/services/bot/platforms/telegram/guestSession.test.tsnew file mode 100644index 00000000000..4b5a4bdb08e--- /dev/null+++ b/apps/server/src/services/bot/platforms/telegram/guestSession.test.ts@@ -0,0 +1,250 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ getTelegramGuestSession,+ getTelegramGuestSessionMemorySizeForTest,+ initializeTelegramGuestSession,+ resetTelegramGuestSessionsForTest,+ saveTelegramGuestSession,+} from './guestSession';++const redisState = vi.hoisted(() => ({+ client: { get: vi.fn(), set: vi.fn() },+ enabled: false,+}));++vi.mock('@/server/modules/AgentRuntime/redis', () => ({+ getAgentRuntimeRedisClient: () => (redisState.enabled ? redisState.client : null),+}));++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ resetTelegramGuestSessionsForTest();+});++describe('telegram guest session (memory fallback)', () => {+ beforeEach(() => {+ redisState.enabled = false;+ });++ it('round-trips a session when Redis is unavailable', async () => {+ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-1',+ });++ await expect(+ getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10'),+ ).resolves.toMatchObject({+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-1',+ });+ });++ it('stamps every save with a write timestamp', async () => {+ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'gq-1',+ });++ const session = await getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10');+ expect(session?.guestQueryId).toBe('gq-1');+ expect(session?.savedAt).toEqual(expect.any(Number));+ });++ it('does not replace an existing outbound session during initialization', async () => {+ const threadId = 'telegram:guest:-1:message:10';+ await saveTelegramGuestSession('bot-1', threadId, {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-1',+ lastText: 'reply',+ mediaType: 'photo',+ });++ await initializeTelegramGuestSession('bot-1', threadId, {+ guestQueryId: 'gq-1',+ locale: 'zh-CN',+ });++ await expect(getTelegramGuestSession('bot-1', threadId)).resolves.toMatchObject({+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-1',+ lastText: 'reply',+ mediaType: 'photo',+ });+ });++ it('isolates sessions by bot and guest invocation', async () => {+ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'bot-1-query-10',+ });+ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:11', {+ guestQueryId: 'bot-1-query-11',+ });+ await saveTelegramGuestSession('bot-2', 'telegram:guest:-1:message:10', {+ guestQueryId: 'bot-2-query-10',+ });++ await expect(+ getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10'),+ ).resolves.toMatchObject({ guestQueryId: 'bot-1-query-10' });+ await expect(+ getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:11'),+ ).resolves.toMatchObject({ guestQueryId: 'bot-1-query-11' });+ await expect(+ getTelegramGuestSession('bot-2', 'telegram:guest:-1:message:10'),+ ).resolves.toMatchObject({ guestQueryId: 'bot-2-query-10' });+ });++ it('evicts expired sessions when later invocations write to memory', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));+ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'expired',+ });++ vi.advanceTimersByTime(30 * 60 * 1000 + 1);+ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:11', {+ guestQueryId: 'current',+ });++ expect(getTelegramGuestSessionMemorySizeForTest()).toBe(1);+ await expect(+ getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10'),+ ).resolves.toBeUndefined();+ });+});++describe('telegram guest session (Redis-backed)', () => {+ const redis = redisState.client;+ const store = new Map<string, string>();++ beforeEach(() => {+ redisState.enabled = true;+ store.clear();+ redis.get.mockImplementation(async (key: string) => store.get(key) ?? null);+ redis.set.mockImplementation(async (key: string, value: string, ...args: unknown[]) => {+ if (args.includes('NX') && store.has(key)) return null;+ store.set(key, value);+ return 'OK';+ });+ });++ afterEach(() => {+ redis.get.mockReset();+ redis.set.mockReset();+ });++ it('serves the Redis copy once memory is gone (webhook -> callback hop)', async () => {+ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-1',+ });+ // Simulate the callback isolate: fresh process, no in-memory state.+ resetTelegramGuestSessionsForTest();++ await expect(+ getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10'),+ ).resolves.toMatchObject({ guestQueryId: 'gq-1', inlineMessageId: 'inline-1' });+ });++ it('atomically initializes without replacing an existing Redis session', async () => {+ const threadId = 'telegram:guest:-1:message:10';+ await saveTelegramGuestSession('bot-1', threadId, {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-1',+ mediaType: 'photo',+ });+ resetTelegramGuestSessionsForTest();++ await initializeTelegramGuestSession('bot-1', threadId, {+ guestQueryId: 'gq-1',+ locale: 'zh-CN',+ });++ expect(redis.set).toHaveBeenLastCalledWith(+ 'bot:telegram-guest:bot-1:telegram:guest:-1:message:10',+ expect.any(String),+ 'EX',+ 30 * 60,+ 'NX',+ );+ await expect(getTelegramGuestSession('bot-1', threadId)).resolves.toMatchObject({+ inlineMessageId: 'inline-1',+ mediaType: 'photo',+ });+ });++ it('prefers the newer in-memory session over stale Redis after a failed set', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-old',+ lastText: 'old',+ });++ // The newer write fails to reach Redis, leaving the stale copy behind.+ vi.advanceTimersByTime(1000);+ redis.set.mockRejectedValueOnce(new Error('redis connection lost'));+ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-new',+ lastText: 'new',+ });+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('failed to persist Telegram guest session'),+ expect.any(Error),+ );++ const session = await getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10');+ expect(session).toMatchObject({ inlineMessageId: 'inline-new', lastText: 'new' });+ });++ it('lets a newer Redis copy win over older memory', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));++ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-old',+ });++ // Another process writes a newer session to Redis after our last local save.+ vi.advanceTimersByTime(1000);+ const key = 'bot:telegram-guest:bot-1:telegram:guest:-1:message:10';+ store.set(+ key,+ JSON.stringify({+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-remote',+ savedAt: Date.now(),+ }),+ );++ await expect(+ getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10'),+ ).resolves.toMatchObject({ inlineMessageId: 'inline-remote' });+ });++ it('falls back to memory and logs loudly when the Redis read fails', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await saveTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10', {+ guestQueryId: 'gq-1',+ inlineMessageId: 'inline-1',+ });++ redis.get.mockRejectedValueOnce(new Error('redis read timeout'));+ const session = await getTelegramGuestSession('bot-1', 'telegram:guest:-1:message:10');+ expect(session).toMatchObject({ inlineMessageId: 'inline-1' });+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('failed to read Telegram guest session'),+ expect.any(Error),+ );+ });+});diff --git a/apps/server/src/services/bot/platforms/telegram/guestSession.ts b/apps/server/src/services/bot/platforms/telegram/guestSession.tsnew file mode 100644index 00000000000..adcaefb0f78--- /dev/null+++ b/apps/server/src/services/bot/platforms/telegram/guestSession.ts@@ -0,0 +1,183 @@+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';++import type { BotReplyLocale } from '../const';++/**+ * Cross-process Guest Mode reply state. The first outbound call answers the+ * guest query; later edits (queue-mode callbacks in a fresh isolate) need the+ * `inline_message_id` that came back.+ *+ * Memory covers same-process local mode; Redis covers the webhook → callback+ * hop. TTL matches the agent execution ceiling.+ */+export interface TelegramGuestSession {+ guestQueryId: string;+ inlineMessageId?: string;+ lastText?: string;+ /**+ * Reply locale derived from the summoning user's Telegram `language_code`.+ * Persisted alongside the session so later edits (possibly in another+ * process via the callback isolate) localize Guest Mode notices the same+ * way as the first reply.+ */+ locale?: BotReplyLocale;+ /**+ * Kind of the current inline message after a successful `editMessageMedia`.+ * Telegram cannot convert a photo back into a text message, so later+ * text-only edits must use `editMessageCaption` instead of `editMessageText`.+ */+ mediaType?: 'photo';+ /**+ * Write timestamp (ms). Used to pick the newer copy when a failed Redis+ * `set` leaves Redis holding an older session than in-process memory.+ * Legacy sessions persisted before this field existed read as `0`.+ */+ savedAt?: number;+ /**+ * Whether an earlier body update exceeded Telegram's single-message limit.+ * Append updates retain the truncation notice even when the stored prefix+ * plus the new chunk would otherwise fit.+ */+ truncated?: boolean;+}++const TTL_SECONDS = 30 * 60;+const memory = new Map<string, { expiresAt: number; session: TelegramGuestSession }>();++const buildKey = (sessionScope: string, threadId: string): string =>+ `bot:telegram-guest:${sessionScope}:${threadId}`;++const pruneExpiredMemory = (now: number): void => {+ for (const [key, entry] of memory) {+ if (entry.expiresAt <= now) memory.delete(key);+ }+};++const readMemory = (key: string): TelegramGuestSession | undefined => {+ const now = Date.now();+ pruneExpiredMemory(now);+ const entry = memory.get(key);+ if (!entry) return undefined;+ return entry.session;+};++const writeMemory = (key: string, session: TelegramGuestSession): void => {+ const now = Date.now();+ pruneExpiredMemory(now);+ memory.set(key, { expiresAt: now + TTL_SECONDS * 1000, session });+};++const writeMemoryIfAbsent = (key: string, session: TelegramGuestSession): void => {+ if (!readMemory(key)) writeMemory(key, session);+};++export async function saveTelegramGuestSession(+ sessionScope: string,+ threadId: string,+ session: TelegramGuestSession,+): Promise<void> {+ const key = buildKey(sessionScope, threadId);+ // Stamp the write time so a later read can tell a stale Redis copy apart+ // from this newer in-memory write.+ const stamped = { ...session, savedAt: Date.now() };+ writeMemory(key, stamped);+ const redis = getAgentRuntimeRedisClient();+ if (!redis) return;+ try {+ await redis.set(key, JSON.stringify(stamped), 'EX', TTL_SECONDS);+ } catch (error) {+ // console (not debug): a failed set means the webhook -> callback handoff+ // may lose this session and the guest reply will later fail with "no+ // session" / "no inline_message_id". Same-process delivery still works+ // off memory, so we do not fail the save itself, but the data-loss risk+ // must stay visible in production logs.+ console.error(+ `[guestSession] failed to persist Telegram guest session to Redis (thread=${threadId}); the reply may be undeliverable from another process`,+ error,+ );+ }+}++/**+ * Creates the inbound Guest Mode session without replacing reply state that+ * may already have been persisted by an earlier delivery of the same webhook.+ */+export async function initializeTelegramGuestSession(+ sessionScope: string,+ threadId: string,+ session: Pick<TelegramGuestSession, 'guestQueryId' | 'locale'>,+): Promise<void> {+ const key = buildKey(sessionScope, threadId);+ if (readMemory(key)) return;++ const stamped = { ...session, savedAt: Date.now() };+ const redis = getAgentRuntimeRedisClient();+ if (!redis) {+ writeMemory(key, stamped);+ return;+ }++ try {+ const created = await redis.set(key, JSON.stringify(stamped), 'EX', TTL_SECONDS, 'NX');+ if (!created) return;++ // An outbound save can complete locally while the Redis command is in+ // flight. Keep that newer local state instead of replacing it with the+ // inbound-only initialization.+ writeMemoryIfAbsent(key, stamped);+ } catch (error) {+ // Redis being unavailable removes the cross-process guarantee, but the+ // same-process fallback must still preserve an existing outbound session.+ writeMemoryIfAbsent(key, stamped);+ console.error(+ `[guestSession] failed to initialize Telegram guest session in Redis (thread=${threadId}); using in-memory state`,+ error,+ );+ }+}++export async function getTelegramGuestSession(+ sessionScope: string,+ threadId: string,+): Promise<TelegramGuestSession | undefined> {+ const key = buildKey(sessionScope, threadId);+ const redis = getAgentRuntimeRedisClient();+ if (redis) {+ try {+ const raw = await redis.get(key);+ if (raw) {+ const redisSession = JSON.parse(raw) as TelegramGuestSession;+ const memorySession = readMemory(key);+ // A transiently failed `set` can leave Redis holding an older copy+ // while this process already holds the newer write. Preferring Redis+ // unconditionally would write the stale copy back over memory and+ // permanently lose the newer `lastText` / `inlineMessageId`, so pick+ // the copy with the newer `savedAt` (ties and legacy unstamped+ // sessions defer to Redis, the cross-process source of truth).+ if (memorySession && (memorySession.savedAt ?? 0) > (redisSession.savedAt ?? 0)) {+ return memorySession;+ }+ writeMemory(key, redisSession);+ return redisSession;+ }+ } catch (error) {+ // Boundary: Redis is the cross-process store; same-process memory is a+ // valid cache holding the newest local write, so a transient read (or+ // corrupt value) failure degrades to the local copy instead of failing+ // the reply. Log loudly since the fallback may be stale or absent.+ console.error(+ `[guestSession] failed to read Telegram guest session from Redis (thread=${threadId}); falling back to in-memory state`,+ error,+ );+ }+ }+ return readMemory(key);+}++/** Test-only: drop in-memory sessions between cases. */+export const resetTelegramGuestSessionsForTest = (): void => {+ memory.clear();+};++/** Test-only: inspect bounded fallback state without exposing the map itself. */+export const getTelegramGuestSessionMemorySizeForTest = (): number => memory.size;diff --git a/apps/server/src/services/bot/platforms/telegram/helpers.test.ts b/apps/server/src/services/bot/platforms/telegram/helpers.test.tsindex e9eb23f027e..d95ae617256 100644--- a/apps/server/src/services/bot/platforms/telegram/helpers.test.ts+++ b/apps/server/src/services/bot/platforms/telegram/helpers.test.ts@@ -5,6 +5,7 @@ import {extractBotId,resolveTelegramSecretToken,setTelegramWebhook,+ TELEGRAM_ALLOWED_UPDATES,} from './helpers';const BOT_TOKEN = '8654315085:AAH-fake-token-for-tests';@@ -64,10 +65,12 @@ describe('setTelegramWebhook', () => {vi.unstubAllGlobals();});- it('always sends secret_token together with the webhook url and allowed_updates', async () => {+ it('always sends secret_token together with the webhook url and allowed_updates including guest_message', async () => {const fetchMock = vi.fn().mockResolvedValue(new Response('{"ok":true}', { status: 200 }));vi.stubGlobal('fetch', fetchMock);+ expect(TELEGRAM_ALLOWED_UPDATES).toContain('guest_message');+await setTelegramWebhook(BOT_TOKEN,'https://cloud.example/api/agent/webhooks/telegram/1',@@ -83,6 +86,7 @@ describe('setTelegramWebhook', () => {url: 'https://cloud.example/api/agent/webhooks/telegram/1',});expect(body.allowed_updates).toContain('message');+ expect(body.allowed_updates).toContain('guest_message');});it('throws with the Telegram error body when the call fails', async () => {diff --git a/apps/server/src/services/bot/platforms/telegram/helpers.ts b/apps/server/src/services/bot/platforms/telegram/helpers.tsindex 5acf5a056e7..16adf4a0fee 100644--- a/apps/server/src/services/bot/platforms/telegram/helpers.ts+++ b/apps/server/src/services/bot/platforms/telegram/helpers.ts@@ -14,11 +14,6 @@ export function extractBotId(botToken: string): string {return botToken.slice(0, colonIndex);}-/**- * Salt used when no server-side key is configured. The derived secret is then- * a pure function of the bot token — still unguessable to anyone who does not- * already hold the token, which is the actual credential.- */const TELEGRAM_WEBHOOK_SECRET_FALLBACK_KEY = 'lobehub-telegram-webhook-secret';/**@@ -58,6 +53,21 @@ export function resolveTelegramSecretToken();}+/**+ * Update types this platform actually handles. Guest Mode summons arrive as+ * `guest_message` and are dropped unless listed — Telegram keeps the previous+ * `allowed_updates` when the field is omitted.+ */+export const TELEGRAM_ALLOWED_UPDATES = [+ 'message',+ 'edited_message',+ 'channel_post',+ 'edited_channel_post',+ 'callback_query',+ 'message_reaction',+ 'guest_message',+] as const;+/*** Call Telegram setWebhook API. Idempotent — safe to call on every startup.*/@@ -67,17 +77,7 @@ export async function setTelegramWebhook(secretToken: string,): Promise<void> {const params: Record<string, unknown> = {- // Explicitly request all update types we need, including group messages.- // Without this, Telegram keeps whatever `allowed_updates` was set previously,- // which may silently exclude group messages.- allowed_updates: [- 'message',- 'edited_message',- 'channel_post',- 'edited_channel_post',- 'callback_query',- 'message_reaction',- ],+ allowed_updates: [...TELEGRAM_ALLOWED_UPDATES],secret_token: secretToken,url,};diff --git a/apps/server/src/services/bot/platforms/telegram/schema.ts b/apps/server/src/services/bot/platforms/telegram/schema.tsindex 4f255959be4..082be7c1ccc 100644--- a/apps/server/src/services/bot/platforms/telegram/schema.ts+++ b/apps/server/src/services/bot/platforms/telegram/schema.ts@@ -5,6 +5,7 @@ import {displayToolCallsField,makeDmPolicyField,makeGroupPolicyFields,+ makeGuestPolicyField,makeUserIdField,watchKeywordsField,} from '../const';@@ -83,6 +84,7 @@ export const schema: FieldSchema[] = [},displayToolCallsField,makeDmPolicyField({ policy: 'open' }),+ makeGuestPolicyField({ policy: 'open' }),...makeGroupPolicyFields({ policy: 'open' }),allowFromField,watchKeywordsField,diff --git a/apps/server/src/services/bot/platforms/telegram/threadId.test.ts b/apps/server/src/services/bot/platforms/telegram/threadId.test.tsnew file mode 100644index 00000000000..5aef3378c52--- /dev/null+++ b/apps/server/src/services/bot/platforms/telegram/threadId.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it } from 'vitest';++import {+ encodeGuestInlineMessageId,+ encodeGuestTelegramThreadId,+ getTelegramGuestAuthorLanguageCode,+ getTelegramGuestQueryId,+ isGuestTelegramThreadId,+ parseTelegramThreadId,+} from './threadId';++describe('parseTelegramThreadId', () => {+ it('parses a member chat id', () => {+ expect(parseTelegramThreadId('telegram:-100123')).toEqual({+ chatId: '-100123',+ guest: false,+ messageThreadId: undefined,+ });+ });++ it('parses a member forum topic', () => {+ expect(parseTelegramThreadId('telegram:-100123:42')).toEqual({+ chatId: '-100123',+ guest: false,+ messageThreadId: 42,+ });+ });++ it('parses a guest chat without treating the guest segment as the chat id', () => {+ expect(parseTelegramThreadId('telegram:guest:-100123')).toEqual({+ chatId: '-100123',+ guest: true,+ messageThreadId: undefined,+ });+ });++ it('parses a guest forum topic', () => {+ expect(parseTelegramThreadId('telegram:guest:-100123:7')).toEqual({+ chatId: '-100123',+ guest: true,+ messageThreadId: 7,+ });+ });++ it('parses a message-scoped guest invocation', () => {+ expect(parseTelegramThreadId('telegram:guest:-100123:bot:999:message:55:7')).toEqual({+ chatId: '-100123',+ guest: true,+ guestBotId: '999',+ guestMessageId: '55',+ messageThreadId: 7,+ });+ });++ it('parses legacy message-scoped guest invocations', () => {+ expect(parseTelegramThreadId('telegram:guest:-100123:message:55:7')).toEqual({+ chatId: '-100123',+ guest: true,+ guestMessageId: '55',+ messageThreadId: 7,+ });+ });+});++describe('isGuestTelegramThreadId / encode', () => {+ it('round-trips guest thread ids', () => {+ const id = encodeGuestTelegramThreadId('-100123', '999', 55, 9);+ expect(id).toBe('telegram:guest:-100123:bot:999:message:55:9');+ expect(isGuestTelegramThreadId(id)).toBe(true);+ expect(isGuestTelegramThreadId('telegram:-100123')).toBe(false);+ });++ it('encodes and decodes guest inline message ids', () => {+ expect(encodeGuestInlineMessageId('BAAAA')).toBe('guest-inline:BAAAA');+ });+});++describe('getTelegramGuestQueryId', () => {+ it('reads guest_query_id from message.raw', () => {+ expect(getTelegramGuestQueryId({ raw: { guest_query_id: 'gq-1' } })).toBe('gq-1');+ expect(getTelegramGuestQueryId({ raw: {} })).toBeUndefined();+ expect(getTelegramGuestQueryId(undefined)).toBeUndefined();+ });+});++describe('getTelegramGuestAuthorLanguageCode', () => {+ it('prefers the summoning user over the message sender', () => {+ expect(+ getTelegramGuestAuthorLanguageCode({+ raw: {+ from: { language_code: 'en' },+ guest_bot_caller_user: { language_code: 'zh-hans' },+ },+ }),+ ).toBe('zh-hans');+ });++ it('falls back to the message sender when no caller user is present', () => {+ expect(getTelegramGuestAuthorLanguageCode({ raw: { from: { language_code: 'pt-br' } } })).toBe(+ 'pt-br',+ );+ });++ it('returns undefined for missing or malformed raw payloads', () => {+ expect(getTelegramGuestAuthorLanguageCode(undefined)).toBeUndefined();+ expect(getTelegramGuestAuthorLanguageCode({ raw: 'nope' })).toBeUndefined();+ expect(getTelegramGuestAuthorLanguageCode({ raw: { from: {} } })).toBeUndefined();+ });+});diff --git a/apps/server/src/services/bot/platforms/telegram/threadId.ts b/apps/server/src/services/bot/platforms/telegram/threadId.tsnew file mode 100644index 00000000000..c03e327b718--- /dev/null+++ b/apps/server/src/services/bot/platforms/telegram/threadId.ts@@ -0,0 +1,120 @@+/**+ * Telegram Chat SDK thread ids:+ *+ * - `telegram:{chatId}` — bot is a member of the chat+ * - `telegram:{chatId}:{messageThreadId}` — forum topic in a member chat+ * - `telegram:guest:{chatId}:bot:{botId}:message:{messageId}` — one Guest Mode summon+ * - `telegram:guest:{chatId}:bot:{botId}:message:{messageId}:{messageThreadId}`+ * — guest summon inside a topic+ *+ * Guest chats MUST NOT share identity with a member chat of the same numeric+ * id — Telegram documents that the two are independent even when the numbers+ * coincide.+ */++const PLATFORM = 'telegram';+const GUEST_SEGMENT = 'guest';++export const TELEGRAM_GUEST_INLINE_ID_PREFIX = 'guest-inline:';++export interface ParsedTelegramThreadId {+ chatId: string;+ guest: boolean;+ guestBotId?: string;+ guestMessageId?: string;+ messageThreadId?: number;+}++export const isGuestTelegramThreadId = (threadId: string): boolean =>+ threadId.startsWith(`${PLATFORM}:${GUEST_SEGMENT}:`);++export const encodeGuestTelegramThreadId = (+ chatId: string,+ botId: string,+ messageId: string | number,+ messageThreadId?: number,+): string => {+ const base = `${PLATFORM}:${GUEST_SEGMENT}:${chatId}:bot:${botId}:message:${messageId}`;+ return typeof messageThreadId === 'number' ? `${base}:${messageThreadId}` : base;+};++export const encodeGuestInlineMessageId = (inlineMessageId: string): string =>+ `${TELEGRAM_GUEST_INLINE_ID_PREFIX}${inlineMessageId}`;++export const decodeGuestInlineMessageId = (messageId: string): string | undefined => {+ if (!messageId.startsWith(TELEGRAM_GUEST_INLINE_ID_PREFIX)) return undefined;+ const id = messageId.slice(TELEGRAM_GUEST_INLINE_ID_PREFIX.length);+ return id.length > 0 ? id : undefined;+};++export const parseTelegramThreadId = (threadId: string): ParsedTelegramThreadId => {+ const parts = threadId.split(':');+ if (parts[0] !== PLATFORM || parts.length < 2) {+ return { chatId: threadId, guest: false };+ }++ if (parts[1] === GUEST_SEGMENT) {+ const chatId = parts[2];+ if (!chatId) return { chatId: threadId, guest: true };++ const asGuest = (+ extra: Omit<ParsedTelegramThreadId, 'chatId' | 'guest'> = {},+ ): ParsedTelegramThreadId => ({ chatId, guest: true, ...extra });++ if (parts[3] === 'bot' && parts[4] && parts[5] === 'message' && parts[6]) {+ return asGuest({+ guestBotId: parts[4],+ guestMessageId: parts[6],+ messageThreadId: parseOptionalThreadId(parts[7]),+ });+ }++ // Backward compatibility for callbacks created before guest thread IDs+ // included the bot application ID.+ if (parts[3] === 'message' && parts[4]) {+ return asGuest({+ guestMessageId: parts[4],+ messageThreadId: parseOptionalThreadId(parts[5]),+ });+ }++ // Backward compatibility for callbacks created before guest invocations+ // gained a message-scoped thread id.+ return asGuest({ messageThreadId: parseOptionalThreadId(parts[3]) });+ }++ return {+ chatId: parts[1]!,+ guest: false,+ messageThreadId: parseOptionalThreadId(parts[2]),+ };+};++const parseOptionalThreadId = (value: string | undefined): number | undefined => {+ if (!value) return undefined;+ const parsed = Number.parseInt(value, 10);+ return Number.isFinite(parsed) ? parsed : undefined;+};++export const getTelegramGuestQueryId = (message?: { raw?: unknown }): string | undefined => {+ if (!message?.raw || typeof message.raw !== 'object') return undefined;+ const id = (message.raw as { guest_query_id?: unknown }).guest_query_id;+ return typeof id === 'string' && id.length > 0 ? id : undefined;+};++/**+ * Telegram `language_code` of the user who summoned the bot in Guest Mode -+ * `guest_bot_caller_user` when present, otherwise the message sender. Used to+ * localize Guest Mode link prompts in the summoner's language.+ */+export const getTelegramGuestAuthorLanguageCode = (message?: {+ raw?: unknown;+}): string | undefined => {+ if (!message?.raw || typeof message.raw !== 'object') return undefined;+ const raw = message.raw as {+ from?: { language_code?: unknown };+ guest_bot_caller_user?: { language_code?: unknown };+ };+ const code = raw.guest_bot_caller_user?.language_code ?? raw.from?.language_code;+ return typeof code === 'string' && code.length > 0 ? code : undefined;+};diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.tsindex 51af4084935..7f6a187c26f 100644--- a/apps/server/src/services/bot/replyTemplate.ts+++ b/apps/server/src/services/bot/replyTemplate.ts@@ -1,6 +1,11 @@import type { StepPresentationData } from '../agentRuntime/types';import { getExtremeAck } from './ackPhrases';-import { type BotReplyLocale, formatDuration } from './platforms';+// Import from the leaf modules (`const` / `utils`) instead of the+// `./platforms` barrel: the barrel instantiates every platform definition+// (and its ClientFactory) at import time, and platform leaf files such as the+// Telegram Guest outbound path import this template for localized copy.+import { type BotReplyLocale } from './platforms/const';+import { formatDuration } from './platforms/utils';// Use raw Unicode emoji instead of Chat SDK emoji placeholders,// because bot-callback webhooks send via DiscordPlatformClient directly@@ -114,7 +119,7 @@ function formatCompletedTools(.join('\n');}-export { formatDuration, formatTokens } from './platforms';+export { formatDuration, formatTokens } from './platforms/utils';function renderProgressHeader(params: { elapsedMs?: number; totalToolCalls?: number },@@ -261,6 +266,25 @@ type SystemStrings = {errorWithId: (operationId: string) => string;groupRejectedAllowlist: string;groupRejectedDisabled: string;+ /**+ * Telegram Guest Mode strings. Unlike the rest of this dictionary these+ * carry Telegram HTML (not Markdown), because the Guest outbound pipeline+ * (`guestOutbound` / `answerGuestQuery`) renders Telegram HTML directly.+ * Locale comes from the summoning user's `language_code`, not the+ * platform default.+ */+ guestAttachmentOverflow: string;+ guestLinkButton: string;+ guestLinkPromptChat: string;+ guestLinkPromptDm: string;+ guestLinkTitle: string;+ guestMediaUnavailable: string;+ guestPairingCapacityExceeded: string;+ guestPairingCode: (code: string) => string;+ guestPairingUnavailable: string;+ guestRejectedAllowlist: string;+ guestRejectedDisabled: string;+ guestTextTruncated: (limit: number) => string;inlineError: (message: string) => string;processing: string;/**@@ -358,6 +382,25 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {"This bot isn't enabled in this channel. Please contact the bot's owner if you need access.",groupRejectedDisabled:"This bot doesn't respond in groups or channels. Please reach out via direct message instead.",+ guestAttachmentOverflow:+ '<i>Additional attachments could not be listed in this Guest Mode reply.</i>',+ guestLinkButton: 'Open Bot',+ guestLinkPromptChat: 'Continue in a private chat with this bot to link your LobeHub account.',+ guestLinkPromptDm:+ 'Open a private chat with this bot and send /start to link your LobeHub account.',+ guestLinkTitle: 'Link LobeHub',+ guestMediaUnavailable: 'This attachment can’t be delivered in Telegram Guest Mode.',+ guestPairingCapacityExceeded:+ 'This bot is handling too many Guest Mode access requests right now. Please try again in a few minutes.',+ guestPairingCode: (code) =>+ `To use this bot in Guest Mode, send this pairing code to the bot's owner: \`${code}\`. They run \`/approve ${code}\` to grant you access. The code expires in 1 hour.`,+ guestPairingUnavailable:+ 'Guest Mode pairing is temporarily unavailable on this bot. Please try again later.',+ guestRejectedAllowlist:+ "Sorry, you aren't authorized to use this bot in Guest Mode. Please contact the bot's owner if you need access.",+ guestRejectedDisabled: 'Guest Mode is disabled for this bot.',+ guestTextTruncated: (limit) =>+ `Response truncated because Telegram Guest Mode supports one ${limit}-character reply.`,inlineError: (message) => `**Error**: ${message}`,processing: 'Processing...',senderRejected:@@ -441,6 +484,21 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {errorWithId: (operationId) => `**Agent 执行失败**\nOperation ID: \`${operationId}\``,groupRejectedAllowlist: '该机器人未在此频道启用。如需访问请联系机器人管理员。',groupRejectedDisabled: '该机器人不在群组或频道中响应。请通过私信联系。',+ guestAttachmentOverflow: '<i>更多附件无法在这条访客模式回复中列出。</i>',+ guestLinkButton: '打开机器人',+ guestLinkPromptChat: '请在私聊中继续,以完成 LobeHub 账户关联。',+ guestLinkPromptDm: '请私聊该机器人并发送 /start,以完成 LobeHub 账户关联。',+ guestLinkTitle: '关联 LobeHub',+ guestMediaUnavailable: '该附件无法通过 Telegram 访客模式送达。',+ guestPairingCapacityExceeded: '该机器人当前待处理的访客模式访问请求过多,请稍后再试。',+ guestPairingCode: (code) =>+ `若要通过访客模式使用该机器人,请把以下配对码发给机器人管理员:\`${code}\`,他们将通过 \`/approve ${code}\` 命令为你授权。配对码 1 小时后失效。`,+ guestPairingUnavailable: '访客模式配对功能暂时不可用,请稍后再试。',+ guestRejectedAllowlist:+ '抱歉,您没有通过访客模式使用该机器人的权限。如需访问请联系机器人管理员。',+ guestRejectedDisabled: '该机器人已禁用访客模式。',+ guestTextTruncated: (limit) =>+ `回复已被截断:Telegram 访客模式仅支持一条 ${limit} 字符的回复。`,inlineError: (message) => `**错误**:${message}`,processing: '处理中…',senderRejected: '抱歉,您没有与该机器人交互的权限。如需访问请联系机器人管理员。',@@ -646,6 +704,31 @@ export function renderCommandReply(key: CommandReplyKey, lng?: BotReplyLocale):return getSystemStrings(lng)[key];}+export type GuestCopyKey =+ | 'guestAttachmentOverflow'+ | 'guestLinkButton'+ | 'guestLinkPromptChat'+ | 'guestLinkPromptDm'+ | 'guestLinkTitle'+ | 'guestMediaUnavailable';++/**+ * Render a Telegram Guest Mode system string (link prompts, truncation and+ * attachment notices). Unlike command replies the locale is not the platform+ * default: a Guest summon can come from any Telegram user, so callers pass+ * the summoning user's normalized `language_code` when known and fall back+ * to the platform default otherwise. The values carry Telegram HTML, not+ * Markdown - the Guest outbound pipeline renders Telegram HTML directly.+ */+export function renderGuestCopy(key: GuestCopyKey, lng?: BotReplyLocale): string {+ return getSystemStrings(lng)[key];+}++/** Truncation notice for the Guest Mode single-reply budget (text 4096 / caption 1024). */+export function renderGuestTruncated(limit: number, lng?: BotReplyLocale): string {+ return getSystemStrings(lng).guestTextTruncated(limit);+}+/*** Render the `/mode` status reply (no-arg invocation). `mode` is the explicit* per-conversation override when one was set via `/mode agent|chat`; undefined@@ -699,6 +782,17 @@ export function renderDmPairing(return strings.dmPairingUnavailable;}+export function renderGuestPairing(+ variant: 'capacity-exceeded' | 'code' | 'unavailable',+ lng?: BotReplyLocale,+ params?: { code?: string },+): string {+ const strings = getSystemStrings(lng);+ if (variant === 'code' && params?.code) return strings.guestPairingCode(params.code);+ if (variant === 'capacity-exceeded') return strings.guestPairingCapacityExceeded;+ return strings.guestPairingUnavailable;+}+/*** Render the system message shown to a sender whose DM was blocked by the* channel's DM Policy. We split disabled vs allowlist so the user can act on@@ -722,6 +816,14 @@ export function renderGroupRejected(return reason === 'disabled' ? strings.groupRejectedDisabled : strings.groupRejectedAllowlist;}+export function renderGuestRejected(+ reason: 'disabled' | 'allowlist',+ lng?: BotReplyLocale,+): string {+ const strings = getSystemStrings(lng);+ return reason === 'disabled' ? strings.guestRejectedDisabled : strings.guestRejectedAllowlist;+}+/*** Render the system message shown when the **global `allowFrom`** gate* rejected the sender of a non-DM event (group / channel / thread). Thediff --git a/apps/server/src/services/messenger/MessengerRouter.test.ts b/apps/server/src/services/messenger/MessengerRouter.test.tsindex 8565da8d61e..e87f286a9fb 100644--- a/apps/server/src/services/messenger/MessengerRouter.test.ts+++ b/apps/server/src/services/messenger/MessengerRouter.test.ts@@ -140,10 +140,12 @@ vi.mock('@/database/models/agent', () => ({}));const mockFindLink = vi.fn();+const mockSetActiveAgentById = vi.fn();const mockSetActiveScope = vi.fn();vi.mock('@/database/models/messengerAccountLink', () => ({MessengerAccountLinkModel: {findByPlatformUser: (...args: any[]) => mockFindLink(...args),+ setActiveAgentById: (...args: unknown[]) => mockSetActiveAgentById(...args),setActiveScope: (...args: any[]) => mockSetActiveScope(...args),},}));@@ -220,11 +222,14 @@ const mockTelegramBinder = {createClient: () => ({createAdapter: () => ({}),// Telegram thread ids are `telegram:<chatId>[:<messageThreadId>]`.- extractChatId: (id: string) => id.split(':')[1] ?? id,+ extractChatId: (id: string) =>+ id.startsWith('telegram:guest:') ? (id.split(':')[2] ?? id) : (id.split(':')[1] ?? id),}),handleUnlinkedMessage: vi.fn(),+ isOneShotMessage: vi.fn().mockReturnValue(false),notifyLinkSuccess: vi.fn(),registerWebhook: vi.fn(),+ replyToMessage: vi.fn(),sendAgentPicker: vi.fn(),sendDmText: vi.fn(),};@@ -295,6 +300,7 @@ beforeEach(() => {wechat: mockWebhookHandler,};mockFindLink.mockReset();+ mockSetActiveAgentById.mockReset();mockSetActiveScope.mockReset();mockListUserWorkspaces.mockReset();mockListUserWorkspaces.mockResolvedValue([@@ -325,6 +331,9 @@ beforeEach(() => {mockSlackBinder.sendAgentPicker.mockReset();mockSlackBinder.sendDmText.mockReset();mockTelegramBinder.handleUnlinkedMessage.mockReset();+ mockTelegramBinder.isOneShotMessage.mockReset();+ mockTelegramBinder.isOneShotMessage.mockReturnValue(false);+ mockTelegramBinder.replyToMessage.mockReset();mockTelegramBinder.sendAgentPicker.mockReset();mockTelegramBinder.sendDmText.mockReset();mockWechatBinder.handleUnlinkedMessage.mockReset();@@ -457,13 +466,15 @@ describe('MessengerRouter.getWebhookHandler', () => {event: { type: 'message' },type: 'event_callback',});- const res = await router.getWebhookHandler('slack')(buildSlackRequest(body));+ const options = { waitUntil: vi.fn() };+ const res = await router.getWebhookHandler('slack')(buildSlackRequest(body), options);expect(res.status).toBe(200);expect(mockWebhookHandler).toHaveBeenCalledTimes(1);// Reconstructed request preserves the body (raw bytes are still readable).- const calls = mockWebhookHandler.mock.calls as unknown as Request[][];+ const calls = mockWebhookHandler.mock.calls as unknown as Array<[Request, typeof options]>;const passedReq = calls[0][0];expect(await passedReq.text()).toBe(body);+ expect(calls[0][1]).toBe(options);});it('skips signature verification for telegram (no headers required)', async () => {@@ -730,6 +741,44 @@ describe('MessengerRouter channel @mention', () => {);});+ it('answers linked Telegram Guest recovery prompts through the one-shot reply', async () => {+ await loadTelegramBot();+ mockFindLink.mockResolvedValue({+ activeAgentId: null,+ id: 'link_1',+ platformUserId: '123',+ tenantId: '',+ userId: 'user_alice',+ workspaceId: null,+ });+ mockTelegramBinder.isOneShotMessage.mockReturnValue(true);++ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (+ thread: any,+ msg: any,+ ) => Promise<void>;+ const message = fakeMessage({+ author: { isBot: false, userId: '123', userName: 'alice' },+ isMention: true,+ raw: { guest_query_id: 'gq-linked' },+ });+ await handler(+ {+ id: 'telegram:guest:-100123:bot:999:message:55',+ isDM: false,+ post: vi.fn(),+ },+ message,+ );++ expect(mockTelegramBinder.replyToMessage).toHaveBeenCalledWith(+ message,+ expect.stringContaining('No active agent'),+ );+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();+ expect(mockTelegramBinder.sendAgentPicker).not.toHaveBeenCalled();+ });+it('scopes the active-agent check to the linked workspace', async () => {await loadSlackBot();mockFindLink.mockResolvedValue({@@ -1989,3 +2038,110 @@ describe('MessengerRouter /switch', () => {);});});++/**+ * @example Guest /agents and /switch replies contain only a DM instruction.+ */+describe('MessengerRouter Telegram Guest command privacy', () => {+ // ROOT CAUSE:+ //+ // Guest Mode disables interactive pickers, so runAgentsCommand and+ // runSwitchCommand fell through to text lists and selection confirmations.+ // replyToMessage publishes those replies in the originating chat, revealing+ // private names and the active selection to other chat participants.+ // The fix redirects Guest commands before reading lists or changing state.+ /**+ * @example /agents 2 in a Guest chat must not switch or expose Private Agent B.+ * @example /switch in a Guest chat must not list Private Workspace.+ */+ it.each([+ '/agents',+ '/agents 1',+ '/agents 2',+ '/agents 99',+ '/switch',+ '/switch 1',+ '/switch 2',+ '/switch 99',+ ])('redirects Guest %s to DM without exposing or changing personal state', async (text) => {+ // Restore earlier grouping spies so these cases exercise real list rendering+ // against the database boundary mocks when run on the unfixed source.+ const fetchUserAgents = Reflect.get(MessengerRouter.prototype, 'fetchUserAgents');+ if (vi.isMockFunction(fetchUserAgents)) fetchUserAgents.mockRestore();+ mockListMessengerBindableAgents.mockResolvedValue([+ { id: 'agt_a', isPrivate: true, title: 'Private Agent A' },+ { id: 'agt_b', isPrivate: true, title: 'Private Agent B' },+ ]);+ mockListUserWorkspaces.mockResolvedValue([+ { id: 'workspace-1', name: 'Private Workspace', role: 'owner' },+ ]);+ await loadTelegramBot();+ mockFindLink.mockResolvedValue({+ activeAgentId: 'agt_a',+ id: 'link_1',+ platformUserId: '123',+ tenantId: '',+ userId: 'user_alice',+ workspaceId: null,+ });+ mockTelegramBinder.isOneShotMessage.mockReturnValue(true);+ const handler = mockChatBot.onNewMention.mock.calls[0][0];+ const message = fakeMessage({+ author: { isBot: false, userId: '123', userName: 'alice' },+ isMention: true,+ raw: { guest_query_id: 'gq-private-command' },+ text,+ });+ await handler(+ { id: 'telegram:guest:-100123:bot:999:message:55', isDM: false, post: vi.fn() },+ message,+ );++ /** @example Exactly one safe reply, without lists, active markers or selection feedback. */+ expect(mockTelegramBinder.replyToMessage.mock.calls).toEqual([+ [+ message,+ `Open your direct message with the LobeHub bot and send \`${text.split(' ')[0]}\` there.`,+ ],+ ]);+ /** @example No picker or extra DM is sent while answering the Guest query. */+ expect(mockTelegramBinder.sendAgentPicker).not.toHaveBeenCalled();+ /** @example The user opens the DM explicitly; the bot does not initiate one. */+ expect(mockTelegramBinder.sendDmText).not.toHaveBeenCalled();+ /** @example /agents 2 cannot change the user's active agent from a Guest chat. */+ expect(mockSetActiveAgentById).not.toHaveBeenCalled();+ /** @example /switch 2 cannot change the user's active workspace from a Guest chat. */+ expect(mockSetActiveScope).not.toHaveBeenCalled();+ });++ /** @example Ordinary Telegram bot DMs continue showing the requested picker. */+ it.each(['/agents', '/switch'])('keeps %s available in an ordinary Telegram DM', async (text) => {+ const fetchUserAgents = Reflect.get(MessengerRouter.prototype, 'fetchUserAgents');+ if (vi.isMockFunction(fetchUserAgents)) fetchUserAgents.mockRestore();+ mockListMessengerBindableAgents.mockResolvedValue([+ { id: 'agt_a', isPrivate: true, title: 'Private Agent A' },+ ]);+ await loadTelegramBot();+ mockFindLink.mockResolvedValue({+ activeAgentId: 'agt_a',+ id: 'link_1',+ platformUserId: '123',+ tenantId: '',+ userId: 'user_alice',+ workspaceId: null,+ });+ const handler = mockChatBot.onNewMention.mock.calls[0][0];+ await handler(+ { id: 'telegram:123', isDM: true, post: vi.fn() },+ fakeMessage({ author: { isBot: false, userId: '123', userName: 'alice' }, text }),+ );++ /** @example The picker remains usable and visible only inside the DM. */+ expect(mockTelegramBinder.sendAgentPicker).toHaveBeenCalledWith(+ '123',+ expect.objectContaining({ ephemeralTo: undefined }),+ );+ /** @example Ordinary DM commands never consume a Guest query. */+ expect(mockTelegramBinder.replyToMessage).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/messenger/MessengerRouter.ts b/apps/server/src/services/messenger/MessengerRouter.tsindex 3b6213ad394..a813bf1bb60 100644--- a/apps/server/src/services/messenger/MessengerRouter.ts+++ b/apps/server/src/services/messenger/MessengerRouter.ts@@ -1,12 +1,7 @@import { createIoRedisState } from '@chat-adapter/state-ioredis';import { agentDisplayName } from '@lobechat/types';-import {- Chat,- ConsoleLogger,- type Message,- type MessageContext,- type SlashCommandEvent,-} from 'chat';+import type { Message, MessageContext, SlashCommandEvent, WebhookOptions } from 'chat';+import { Chat, ConsoleLogger } from 'chat';import debug from 'debug';import { getBotFeatureAccessState } from '@/business/server/bot/featureAccess';@@ -103,6 +98,8 @@ interface MessengerCommandContext {* follow-up webhook, otherwise Discord shows "Thinking..." indefinitely* and eventually flips to "The application did not respond". */interaction?: { applicationId: string; token: string };+ /** Whether this invocation can receive a follow-up interactive picker. */+ interactiveReplies: boolean;/** True when the command was invoked from a 1:1 DM. Commands that surface* user-private UI (e.g. `/agents` picker) widen private replies into* ephemerals when this is false so the channel doesn't see them. */@@ -275,8 +272,10 @@ export class MessengerRouter {* that chat-sdk doesn't surface* 6. Otherwise hand the (reconstructed) request to chat-sdk's webhook handler*/- getWebhookHandler(platform: string): (req: Request) => Promise<Response> {- return async (req: Request) => {+ getWebhookHandler(+ platform: string,+ ): (req: Request, options?: WebhookOptions) => Promise<Response> {+ return async (req: Request, options?: WebhookOptions) => {const definition = messengerPlatformRegistry.getPlatform(platform);if (!definition) {return new Response(`Unknown messenger platform: ${platform}`, { status: 404 });@@ -346,7 +345,7 @@ export class MessengerRouter {if (!handler) {return new Response(`Messenger ${platform} webhook unavailable`, { status: 500 });}- return handler(reconstructRequest(req, rawBody));+ return handler(reconstructRequest(req, rawBody), options);};}@@ -482,7 +481,14 @@ export class MessengerRouter {// which the binder splits when posting in-thread.const isChannelMention = thread.isDM === false;const channelThreadTs = isChannelMention ? String(thread.id).split(':')[2] : undefined;+ const isOneShotMessage = binder.isOneShotMessage?.(message) === true;+ let oneShotReplySent = false;const replyToSender = (text: string): Promise<void> => {+ if (isOneShotMessage && binder.replyToMessage) {+ if (oneShotReplySent) return Promise.resolve();+ oneShotReplySent = true;+ return binder.replyToMessage(message, text);+ }if (isChannelMention && binder.replyEphemeral) {return binder.replyEphemeral({channelId: chatId,@@ -519,6 +525,7 @@ export class MessengerRouter {authorUserName: message.author.userName,binder,chatId,+ interactiveReplies: !isOneShotMessage,isDM: !isChannelMention,link,message,@@ -864,7 +871,7 @@ export class MessengerRouter {// Only nudge the user toward DM when the link actually went there.// For the Slack ephemeral path the prompt is already inline, a// second "check your DM" would be misleading.- if (!ctx.isDM && !canEphemeralInChannel) {+ if (!ctx.isDM && !canEphemeralInChannel && ctx.interactiveReplies) {await ctx.reply(strings.checkDirectMessage);}},@@ -976,7 +983,11 @@ export class MessengerRouter {// channel text mention resolves the CHANNEL thread — picker taps// would write the DM while this channel's next run reads its own// state — so it gets the text status instead.- if (ctx.binder.sendAgentPicker && (ctx.isDM || ctx.source === 'slash')) {+ if (+ ctx.interactiveReplies &&+ ctx.binder.sendAgentPicker &&+ (ctx.isDM || ctx.source === 'slash')+ ) {await ctx.binder.sendAgentPicker(ctx.chatId, {action: 'mode',entries: MessengerRouter.modePickerEntries(current, strings),@@ -1215,6 +1226,7 @@ export class MessengerRouter {binder,chatId: replyChatId,interaction,+ interactiveReplies: true,// `isDM` lets handlers like `/agents` keep the picker public in// DMs (so it stays in history) and widen to an ephemeral when// the slash was typed from a public channel.@@ -1242,11 +1254,34 @@ export class MessengerRouter {* active one — on platforms that implement `sendAgentPicker` the bot replies* with a tap-to-switch keyboard. Platforms without keyboard support fall* back to a numbered text list + `/agents <n>` syntax for switching.+ *+ * Use when:+ * - A registered /agents text or slash command reaches the router.+ *+ * Expects:+ * - The context identifies whether Telegram can send interactive replies.+ *+ * Returns:+ * - A private selection response, or a safe DM instruction for Guest Mode.+ *+ * Triggering workflow / Call stack:+ *+ * {@link registerHandlers} / {@link handleSlashCommand}+ * -> {@link buildCommands} (`/agents`)+ * -> {@link runAgentsCommand}+ * -> {@link MessengerCommandContext.reply} / {@link MessengerPlatformBinder.sendAgentPicker}*/private async runAgentsCommand(ctx: MessengerCommandContext): Promise<void> {const { binder, chatId, link, serverDB } = ctx;const strings = getMessengerSystemStrings(ctx.platform);+ // Telegram Guest replies are visible in the originating chat. Redirect+ // before fetching personal data or switching state, including /agents <n>.+ if (ctx.platform === 'telegram' && !ctx.interactiveReplies) {+ await ctx.reply(strings.agentsDirectMessageOnly);+ return;+ }+if (!link) {await ctx.reply(strings.needLink);return;@@ -1261,7 +1296,7 @@ export class MessengerRouter {// Text-fallback path: `/agents 2` switches without needing the keyboard,// for platforms (or clients) where tap-buttons aren't available.const args = ctx.args.trim();- if (args && !binder.sendAgentPicker) {+ if (args && (!binder.sendAgentPicker || !ctx.interactiveReplies)) {const index = Number.parseInt(args, 10);if (!Number.isInteger(index) || index < 1 || index > userAgents.length) {await ctx.reply(strings.agentsUsage(userAgents.length));@@ -1277,7 +1312,7 @@ export class MessengerRouter {return;}- if (binder.sendAgentPicker) {+ if (binder.sendAgentPicker && ctx.interactiveReplies) {await binder.sendAgentPicker(chatId, {entries: this.toPickerEntries(userAgents, link.activeAgentId, strings),// Channel invocation → render ephemeral so only the invoker sees@@ -1348,10 +1383,33 @@ export class MessengerRouter {* replies with a tap-to-switch keyboard (buttons emit `messenger:scope:<id>`* so the callback path can tell them apart from agent switches). Platforms* without keyboard support fall back to a numbered text list + `/switch <n>`.+ *+ * Use when:+ * - A registered /switch text or slash command reaches the router.+ *+ * Expects:+ * - The context identifies whether Telegram can send interactive replies.+ *+ * Returns:+ * - A private selection response, or a safe DM instruction for Guest Mode.+ *+ * Triggering workflow / Call stack:+ *+ * {@link registerHandlers} / {@link handleSlashCommand}+ * -> {@link buildCommands} (`/switch`)+ * -> {@link runSwitchCommand}+ * -> {@link MessengerCommandContext.reply} / {@link MessengerPlatformBinder.sendAgentPicker}*/private async runSwitchCommand(ctx: MessengerCommandContext): Promise<void> {const { binder, chatId, link, serverDB } = ctx;const strings = getMessengerSystemStrings(ctx.platform);++ // Telegram Guest replies are visible in the originating chat. Redirect+ // before fetching personal data or switching state, including /switch <n>.+ if (ctx.platform === 'telegram' && !ctx.interactiveReplies) {+ await ctx.reply(strings.switchDirectMessageOnly);+ return;+ }if (!link) {await ctx.reply(strings.needLink);return;@@ -1362,7 +1420,7 @@ export class MessengerRouter {// Text-fallback path: `/switch 2` switches without needing the keyboard,// for platforms (or clients) where tap-buttons aren't available.const arg = ctx.args.trim();- if (arg && !binder.sendAgentPicker) {+ if (arg && (!binder.sendAgentPicker || !ctx.interactiveReplies)) {const index = Number.parseInt(arg, 10);if (!Number.isInteger(index) || index < 1 || index > scopes.length) {await ctx.reply(strings.scopesUsage(scopes.length));@@ -1378,7 +1436,7 @@ export class MessengerRouter {return;}- if (binder.sendAgentPicker) {+ if (binder.sendAgentPicker && ctx.interactiveReplies) {await binder.sendAgentPicker(chatId, {action: 'scope',entries: this.toScopeEntries(scopes, link.workspaceId ?? null),diff --git a/apps/server/src/services/messenger/platforms/telegram/binder.test.ts b/apps/server/src/services/messenger/platforms/telegram/binder.test.tsindex 4ff8dedca2c..02a02b24bdb 100644--- a/apps/server/src/services/messenger/platforms/telegram/binder.test.ts+++ b/apps/server/src/services/messenger/platforms/telegram/binder.test.ts@@ -40,6 +40,7 @@ let sendMessageWithUrlButton: ReturnType<typeof vi.fn>;let sendMessageWithCallbackKeyboard: ReturnType<typeof vi.fn>;let editMessageWithCallbackKeyboard: ReturnType<typeof vi.fn>;let answerCallbackQuery: ReturnType<typeof vi.fn>;+let answerGuestArticle: ReturnType<typeof vi.fn>;beforeEach(() => {sendMessage = vi.fn().mockResolvedValue({ message_id: 1 });@@ -47,11 +48,13 @@ beforeEach(() => {sendMessageWithCallbackKeyboard = vi.fn().mockResolvedValue({ message_id: 3 });editMessageWithCallbackKeyboard = vi.fn().mockResolvedValue(undefined);answerCallbackQuery = vi.fn().mockResolvedValue(undefined);+ answerGuestArticle = vi.fn().mockResolvedValue({ inline_message_id: 'inline-1' });vi.mocked(TelegramApi).mockImplementation(() =>({answerCallbackQuery,+ answerGuestArticle,editMessageWithCallbackKeyboard,sendMessage,sendMessageWithCallbackKeyboard,@@ -172,6 +175,76 @@ describe('MessengerTelegramBinder.handleUnlinkedMessage', () => {expect(sendMessageWithUrlButton).not.toHaveBeenCalled();});+ it('answers a Guest Mode summon via answerGuestQuery instead of sendMessage', async () => {+ const binder = new MessengerTelegramBinder();+ await binder.handleUnlinkedMessage({+ authorUserId: '12345',+ authorUserName: 'alice',+ chatId: '-100999',+ message: { id: 'm1', raw: { guest_query_id: 'gq-99' } } as any,+ });++ expect(answerGuestArticle).toHaveBeenCalledTimes(1);+ const [guestQueryId, text, extra] = answerGuestArticle.mock.calls[0];+ expect(guestQueryId).toBe('gq-99');+ expect(text).toContain('private chat');+ expect(extra.replyMarkup.inline_keyboard[0][0]).toEqual({+ text: 'Open Bot',+ url: 'https://t.me/lobehub_bot?start=link',+ });+ expect(issueLinkToken).not.toHaveBeenCalled();+ expect(sendMessageWithUrlButton).not.toHaveBeenCalled();+ expect(sendMessage).not.toHaveBeenCalled();+ });++ it('does not issue a public link token when the bot username is missing', async () => {+ vi.mocked(getMessengerTelegramConfig).mockResolvedValueOnce({+ botToken: 'tg-bot-token',+ } as any);++ await new MessengerTelegramBinder().handleUnlinkedMessage({+ authorUserId: '12345',+ chatId: '-100999',+ message: { id: 'm1', raw: { guest_query_id: 'gq-99' } } as any,+ });++ expect(issueLinkToken).not.toHaveBeenCalled();+ expect(answerGuestArticle).toHaveBeenCalledWith(+ 'gq-99',+ expect.stringContaining('send /start'),+ expect.objectContaining({ title: 'Link LobeHub' }),+ );+ expect(answerGuestArticle.mock.calls[0]?.[2]?.replyMarkup).toBeUndefined();+ });++ it('localizes the Guest Mode link prompt to the summoner language', async () => {+ const binder = new MessengerTelegramBinder();+ await binder.handleUnlinkedMessage({+ authorUserId: '12345',+ authorUserName: 'alice',+ chatId: '-100999',+ message: {+ id: 'm1',+ raw: {+ from: { id: 7, language_code: 'en' },+ guest_bot_caller_user: { id: 7, language_code: 'zh-hans' },+ guest_query_id: 'gq-zh',+ },+ } as any,+ });++ expect(answerGuestArticle).toHaveBeenCalledTimes(1);+ const [guestQueryId, text, extra] = answerGuestArticle.mock.calls[0];+ expect(guestQueryId).toBe('gq-zh');+ expect(text).toBe('请在私聊中继续,以完成 LobeHub 账户关联。');+ expect(text).not.toContain('private chat');+ expect(extra.replyMarkup.inline_keyboard[0][0]).toMatchObject({+ text: '打开机器人',+ url: 'https://t.me/lobehub_bot?start=link',+ });+ expect(extra.title).toBe('关联 LobeHub');+ });+it('no-ops when telegram is not configured', async () => {vi.mocked(getMessengerTelegramConfig).mockResolvedValueOnce(null);const binder = new MessengerTelegramBinder();@@ -241,6 +314,28 @@ describe('MessengerTelegramBinder.notifyLinkSuccess', () => {});});+describe('MessengerTelegramBinder Guest Mode replies', () => {+ it('identifies messages that require a one-shot Guest reply', () => {+ const binder = new MessengerTelegramBinder();+ expect(binder.isOneShotMessage({ raw: { guest_query_id: 'gq-1' } } as any)).toBe(true);+ expect(binder.isOneShotMessage({ raw: {} } as any)).toBe(false);+ });++ it('answers linked-user system text through answerGuestQuery', async () => {+ const binder = new MessengerTelegramBinder();+ await binder.replyToMessage(+ { raw: { guest_query_id: 'gq-linked' } } as any,+ 'No active agent. Run /agents <1>.',+ );++ expect(answerGuestArticle).toHaveBeenCalledWith(+ 'gq-linked',+ 'No active agent. Run /agents <1>.',+ );+ expect(sendMessage).not.toHaveBeenCalled();+ });+});+describe('MessengerTelegramBinder.sendDmText', () => {it('HTML-escapes the text before sending', async () => {const binder = new MessengerTelegramBinder();diff --git a/apps/server/src/services/messenger/platforms/telegram/binder.ts b/apps/server/src/services/messenger/platforms/telegram/binder.tsindex 496ae8bacd5..70fb6b86dcb 100644--- a/apps/server/src/services/messenger/platforms/telegram/binder.ts+++ b/apps/server/src/services/messenger/platforms/telegram/binder.ts@@ -1,10 +1,17 @@+import type { Message } from 'chat';import debug from 'debug';import { getMessengerTelegramConfig } from '@/config/messenger';import { appEnv } from '@/envs/app';import type { PlatformClient } from '@/server/services/bot/platforms';+import { getBotReplyLocale, normalizeBotReplyLocale } from '@/server/services/bot/platforms/const';import { TelegramApi } from '@/server/services/bot/platforms/telegram/api';import { TelegramClientFactory } from '@/server/services/bot/platforms/telegram/client';+import {+ getTelegramGuestAuthorLanguageCode,+ getTelegramGuestQueryId,+} from '@/server/services/bot/platforms/telegram/threadId';+import { renderGuestCopy } from '@/server/services/bot/replyTemplate';import { issueLinkToken } from '../../linkTokenStore';import type {@@ -93,6 +100,36 @@ export class MessengerTelegramBinder implements MessengerPlatformBinder {const config = await getMessengerTelegramConfig();if (!config) return;+ const guestQueryId = getTelegramGuestQueryId(ctx.message);+ const api = new TelegramApi(config.botToken);+ if (guestQueryId) {+ // Guest summons can come from any Telegram locale; render the link+ // prompts in the summoning user's language when Telegram reports one,+ // falling back to the platform default.+ const lng =+ normalizeBotReplyLocale(getTelegramGuestAuthorLanguageCode(ctx.message)) ??+ getBotReplyLocale('telegram');+ const botUsername = config.botUsername?.replace(/^@/, '').trim();+ const text = renderGuestCopy(botUsername ? 'guestLinkPromptChat' : 'guestLinkPromptDm', lng);+ const replyMarkup = botUsername+ ? {+ inline_keyboard: [+ [+ {+ text: renderGuestCopy('guestLinkButton', lng),+ url: `https://t.me/${encodeURIComponent(botUsername)}?start=link`,+ },+ ],+ ],+ }+ : undefined;+ await api.answerGuestArticle(guestQueryId, text, {+ replyMarkup,+ title: renderGuestCopy('guestLinkTitle', lng),+ });+ return;+ }+// The verify-im button takes the user back into LobeHub for the auth /// session-bound binding flow, so it must use APP_URL — same as every other// app-side redirect — not the webhook tunnel URL. (Tunnel URLs are only@@ -103,6 +140,11 @@ export class MessengerTelegramBinder implements MessengerPlatformBinder {return;}+ const postUnlinked = (text: string, button?: { text: string; url: string }) =>+ button+ ? api.sendMessageWithUrlButton(ctx.chatId, text, button)+ : api.sendMessage(ctx.chatId, text);+let randomId: string;try {randomId = await issueLinkToken({@@ -112,11 +154,7 @@ export class MessengerTelegramBinder implements MessengerPlatformBinder {});} catch (error) {log('handleUnlinkedMessage: failed to issue link token: %O', error);- const api = new TelegramApi(config.botToken);- await api.sendMessage(- ctx.chatId,- 'LobeHub is temporarily unavailable. Please try again in a moment.',- );+ await postUnlinked('LobeHub is temporarily unavailable. Please try again in a moment.');return;}@@ -126,24 +164,34 @@ export class MessengerTelegramBinder implements MessengerPlatformBinder {randomId,});- const api = new TelegramApi(config.botToken);-if (isLocalhostUrl(verifyUrl)) {log('handleUnlinkedMessage: APP_URL is localhost, falling back to plain text link');const text = `Welcome to LobeHub! 🤖\n\nTo continue, link your Telegram account to LobeHub. The link expires in 30 minutes:\n\n${verifyUrl}\n\nAfter linking, send /agents anytime to list your agents and tap one to switch the active agent.`;- await api.sendMessage(ctx.chatId, text);+ await postUnlinked(text);return;}const text ='Welcome to LobeHub! 🤖\n\nTo continue, link your Telegram account to LobeHub.\n\nTap the button below — the link expires in 30 minutes.\n\nAfter linking, send /agents anytime to list your agents and tap one to switch the active agent.';- await api.sendMessageWithUrlButton(ctx.chatId, text, {+ await postUnlinked(text, {text: '🔗 Link Account',url: verifyUrl,});}+ isOneShotMessage(message: Message): boolean {+ return Boolean(getTelegramGuestQueryId(message));+ }++ async replyToMessage(message: Message, text: string): Promise<void> {+ const guestQueryId = getTelegramGuestQueryId(message);+ if (!guestQueryId) return;+ const config = await getMessengerTelegramConfig();+ if (!config) return;+ await new TelegramApi(config.botToken).answerGuestArticle(guestQueryId, escapeHtml(text));+ }+async notifyLinkSuccess(params: {activeAgentName?: string;platformUserId: string;diff --git a/apps/server/src/services/messenger/systemReply.ts b/apps/server/src/services/messenger/systemReply.tsindex a3f0de1f59c..d646f78dbab 100644--- a/apps/server/src/services/messenger/systemReply.ts+++ b/apps/server/src/services/messenger/systemReply.ts@@ -8,6 +8,8 @@ interface MessengerSystemStrings {activeAgentChangedToast: (title: string) => string;activeMarker: string;agentNotFound: string;+ /** Safe instruction when agent selection cannot be shown privately. */+ agentsDirectMessageOnly: string;agentsEmpty: string;agentsHeading: string;agentsHint: string;@@ -46,6 +48,8 @@ interface MessengerSystemStrings {stopNotActive: string;stopRequested: string;stopUnable: string;+ /** Safe instruction when workspace selection cannot be shown privately. */+ switchDirectMessageOnly: string;unknownAction: string;unknownCommand: (name: string) => string;}@@ -60,6 +64,8 @@ const EN_US: MessengerSystemStrings = {activeAgentChangedToast: (title) => `Switched to ${title}.`,activeMarker: 'active',agentNotFound: 'Agent not found.',+ agentsDirectMessageOnly:+ 'Open your direct message with the LobeHub bot and send `/agents` there.',agentsEmpty: 'You have no agents yet. Create one in LobeHub, then come back to /agents.',agentsHeading: 'Your agents:',agentsHint: 'Reply with /agents <n> to switch the active agent.',@@ -112,6 +118,8 @@ const EN_US: MessengerSystemStrings = {stopNotActive: 'No active execution to stop.',stopRequested: 'Stop requested.',stopUnable: 'Unable to stop the current execution.',+ switchDirectMessageOnly:+ 'Open your direct message with the LobeHub bot and send `/switch` there.',unknownAction: 'Unknown action.',unknownCommand: (name) => `Unknown command: /${name}`,};@@ -125,6 +133,7 @@ const ZH_CN: MessengerSystemStrings = {activeAgentChangedToast: (title) => `已切换到 ${title}。`,activeMarker: '当前',agentNotFound: '未找到该 Agent。',+ agentsDirectMessageOnly: '请在与 LobeHub 机器人的私聊中发送 `/agents`。',agentsEmpty: '你还没有 Agent。请先在 LobeHub 创建,然后再发送 /agents。',agentsHeading: '你的 Agent:',agentsHint: '回复 /agents <序号> 可切换当前 Agent。',@@ -175,6 +184,7 @@ const ZH_CN: MessengerSystemStrings = {stopNotActive: '当前没有正在执行的任务可以停止。',stopRequested: '已发出停止请求。',stopUnable: '无法停止当前执行。',+ switchDirectMessageOnly: '请在与 LobeHub 机器人的私聊中发送 `/switch`。',unknownAction: '未知操作。',unknownCommand: (name) => `未知命令:/${name}`,};diff --git a/apps/server/src/services/messenger/types.ts b/apps/server/src/services/messenger/types.tsindex 6a706ec02c6..76a9445785d 100644--- a/apps/server/src/services/messenger/types.ts+++ b/apps/server/src/services/messenger/types.ts@@ -122,6 +122,9 @@ export interface MessengerPlatformBinder {/** Called when an inbound message arrives from a sender that hasn't bound any account yet. */handleUnlinkedMessage: (ctx: UnlinkedMessageContext) => Promise<void>;+ /** Whether this inbound message accepts exactly one platform-specific reply. */+ isOneShotMessage?: (message: Message) => boolean;+/*** Best-effort confirmation back to the IM thread once verify-im writes the* link row. `activeAgentName` is included when the verify-im flow set an@@ -172,6 +175,9 @@ export interface MessengerPlatformBinder {text: string,) => Promise<void>;+ /** Reply through the one-shot mechanism identified by `isOneShotMessage`. */+ replyToMessage?: (message: Message, text: string) => Promise<void>;+/*** Send an interactive agent picker so the user can switch the active agent* without typing a number. Optional — platforms that don't supportdiff --git a/docs/usage/channels/telegram.mdx b/docs/usage/channels/telegram.mdxindex 9feba2099fa..db30050c642 100644--- a/docs/usage/channels/telegram.mdx+++ b/docs/usage/channels/telegram.mdx@@ -95,13 +95,23 @@ To use the bot in Telegram groups:**About Group Privacy Mode:** Telegram bots have privacy mode enabled by default, which means they only receive messages that @mention the bot, reply to the bot, or contain /commands. If you change the privacy mode setting after creating the bot, you **must remove and re-add the bot to the group** for the new setting to take effect in that group.</Callout>+## Guest Mode (summon without joining)++Telegram [Guest Mode](https://core.telegram.org/bots/features#guest-bots) lets people `@mention` your bot in any group or private chat **without adding it as a member**. The bot sees only the summoning message (and the message it was replying to, if any) and can post one reply.++1. Open [@BotFather](https://t.me/BotFather)'s Mini App → your bot → enable **Guest Mode**+2. Anyone can then write `@your_bot_username …` in a chat the bot has never joined+3. Replies to that guest message summon the bot again in the same chat++Guest summons use their own **Guest Policy** and are not gated by **Group Policy**. Keyword watch and always-on group traffic still require adding the bot as a member.+## Access Policies-Two independent policies gate inbound traffic. Both default to **Open**.+Three independent policies gate inbound traffic. All default to **Open**.### Allowed User IDs (global)-A populated **Allowed User IDs** field acts as a global gate — DMs *and* group `@mentions` are restricted to listed Telegram numeric user IDs. Empty means "no user-level filter". Grab a user's numeric ID via [@userinfobot](https://t.me/userinfobot), or read the `from.id` field from the bot's incoming update.+A populated **Allowed User IDs** field acts as a global gate — DMs, group `@mentions`, and Guest Mode summons are restricted to listed Telegram numeric user IDs. Empty means "no user-level filter". Grab a user's numeric ID via [@userinfobot](https://t.me/userinfobot), or read the `from.id` field from the bot's incoming update.### DM Policy@@ -118,18 +128,28 @@ Controls which Telegram groups / channels the bot will respond in.- **Allowlist** — Respond only in chats whose ID is listed in **Allowed Channel IDs**. Forward a message from the chat to [@userinfobot](https://t.me/userinfobot) to grab the chat ID (group IDs are negative).- **Disabled** — Ignore all group traffic; the bot only responds to DMs.+### Guest Policy++Controls who can summon the bot through Telegram Guest Mode without adding it to the chat.++- **Open (default)** — Accept Guest Mode summons from anyone. A populated **Allowed User IDs** list still acts as a global user gate.+- **Allowlist** — Only users in **Allowed User IDs** can summon the bot. An empty list fails closed.+- **Pairing** — Non-listed users receive a one-time pairing code in the Guest reply. Approve via `/approve <code>` and ask them to summon the bot again. Requires **Your Platform User ID** and Redis.+- **Disabled** — Reject all Guest Mode summons. This does not affect DMs or groups the bot has joined.+See the [Channels overview](/docs/usage/channels/overview#direct-message-policy) for cross-platform details.## Configuration Reference-| Field | Required | Description |-| ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------- |-| **Bot Token** | Yes | API token from BotFather |-| **Webhook Secret Token** | No | Optional secret for verifying webhook requests |-| **Allowed User IDs** | No | Comma- or whitespace-separated Telegram numeric user IDs. Global gate — applies to DMs and group @mentions |-| **DM Policy** | No | `open` (default), `allowlist`, `pairing`, or `disabled` — who is allowed to DM the bot |-| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the bot responds in groups |-| **Allowed Channel IDs** | No | Comma- or whitespace-separated Telegram chat IDs (group IDs are negative). Used when Group Policy is Allowlist |+| Field | Required | Description |+| ------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------- |+| **Bot Token** | Yes | API token from BotFather |+| **Webhook Secret Token** | No | Optional secret for verifying webhook requests |+| **Allowed User IDs** | No | Comma- or whitespace-separated Telegram numeric user IDs. Global gate — applies to DMs, group @mentions, and Guest Mode |+| **DM Policy** | No | `open` (default), `allowlist`, `pairing`, or `disabled` — who is allowed to DM the bot |+| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the bot responds in groups |+| **Guest Policy** | No | `open` (default), `allowlist`, `pairing`, or `disabled` — who can use Telegram Guest Mode |+| **Allowed Channel IDs** | No | Comma- or whitespace-separated Telegram chat IDs (group IDs are negative). Used when Group Policy is Allowlist |## Troubleshootingdiff --git a/docs/usage/channels/telegram.zh-CN.mdx b/docs/usage/channels/telegram.zh-CN.mdxindex 89ed4a13ca7..6415dd22241 100644--- a/docs/usage/channels/telegram.zh-CN.mdx+++ b/docs/usage/channels/telegram.zh-CN.mdx@@ -94,13 +94,23 @@ tags:**关于隐私模式(Group Privacy):** Telegram 机器人默认启用隐私模式,仅接收群组中 @提及、回复机器人的消息以及 / 命令。如果您在创建机器人后更改了隐私模式设置,**必须将机器人从群组中移除后重新加入**,新的设置才会对该群组生效。</Callout>+## Guest Mode(无需入群即可召唤)++Telegram [Guest Mode](https://core.telegram.org/bots/features#guest-bots) 允许用户在任意群组或私聊中 `@mention` 你的机器人,**不必把机器人加为成员**。机器人只能看到这条召唤消息(以及它所回复的那条,如果有),并且只能回复一次。++1. 打开 [@BotFather](https://t.me/BotFather) 的 Mini App → 选择你的机器人 → 开启 **Guest Mode**+2. 之后任何人都可以在机器人从未加入的会话里发送 `@your_bot_username …`+3. 回复这条访客消息会再次召唤机器人++Guest 召唤使用独立的 **访客模式策略**,不受 **群组策略** 限制。关键词唤醒和常驻群聊流量仍需要把机器人加进群。+## 接入策略-两个独立的策略控制入站消息,默认都为 **开放**。+三个独立的策略控制入站消息,默认都为 **开放**。### 允许的用户 ID(全局)-填入 **允许的用户 ID** 后,**所有**入站消息(私信和群聊 `@提及`)都必须来自列表里的 Telegram 数字用户 ID。留空则不做用户级过滤。让目标用户私信 [@userinfobot](https://t.me/userinfobot) 拿到自己的数字 ID,或直接从机器人收到的 update 里读 `from.id`。+填入 **允许的用户 ID** 后,**所有**入站消息(私信、群聊 `@提及` 和 Guest 召唤)都必须来自列表里的 Telegram 数字用户 ID。留空则不做用户级过滤。让目标用户私信 [@userinfobot](https://t.me/userinfobot) 拿到自己的数字 ID,或直接从机器人收到的 update 里读 `from.id`。### 私信策略@@ -117,18 +127,28 @@ tags:- **白名单 (Allowlist)** — 只在 **允许的频道 ID** 列出的会话里响应。把群里的一条消息转发给 [@userinfobot](https://t.me/userinfobot) 即可拿到 chat ID(群组是负数)。- **禁用 (Disabled)** — 忽略所有群组流量,机器人只接受私信。+### 访客模式策略++控制谁可以在不把机器人加入会话的情况下,通过 Telegram Guest Mode 召唤机器人。++- **开放 (Open)(默认)** — 接受任何人的 Guest 召唤。若 **允许的用户 ID** 非空,它仍会作为全局用户闸门生效。+- **白名单 (Allowlist)** — 只有 **允许的用户 ID** 中的用户可以召唤。名单为空时全部拒绝。+- **配对审批 (Pairing)** — 非名单用户会在 Guest 回复中收到一次性配对码。通过 `/approve <code>` 审批后,请用户重新召唤机器人。需要配置 **你的平台用户 ID** 和 Redis。+- **禁用 (Disabled)** — 拒绝所有 Guest 召唤,不影响私信或机器人已加入的群组。+跨平台细节见 [渠道概览](/docs/usage/channels/overview#direct-message-policy)。## 配置参考-| 字段 | 是否必需 | 描述 |-| ---------------- | ---- | ---------------------------------------------------------- |-| **机器人令牌** | 是 | 来自 BotFather 的 API 令牌 |-| **Webhook 密钥令牌** | 否 | 用于验证 Webhook 请求的可选密钥 |-| **允许的用户 ID** | 否 | 逗号或空格分隔的 Telegram 数字用户 ID。全局闸门 — 私信和群聊 @ 都受其约束 |-| **私信策略** | 否 | `open`(默认)、`allowlist`、`pairing` 或 `disabled` — 控制谁可以私信机器人 |-| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些群组中响应 |-| **允许的频道 ID** | 否 | 逗号或空格分隔的 Telegram chat ID(群组为负数)。仅在群组策略为白名单时使用 |+| 字段 | 是否必需 | 描述 |+| ---------------- | ---- | ----------------------------------------------------------- |+| **机器人令牌** | 是 | 来自 BotFather 的 API 令牌 |+| **Webhook 密钥令牌** | 否 | 用于验证 Webhook 请求的可选密钥 |+| **允许的用户 ID** | 否 | 逗号或空格分隔的 Telegram 数字用户 ID。全局闸门 — 私信、群聊 @ 和访客模式都受其约束 |+| **私信策略** | 否 | `open`(默认)、`allowlist`、`pairing` 或 `disabled` — 控制谁可以私信机器人 |+| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些群组中响应 |+| **访客模式策略** | 否 | `open`(默认)、`allowlist`、`pairing` 或 `disabled` — 控制谁可以使用访客模式 |+| **允许的频道 ID** | 否 | 逗号或空格分隔的 Telegram chat ID(群组为负数)。仅在群组策略为白名单时使用 |## 故障排除diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 65ed4618ed0..9879b26ba68 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -2,7 +2,7 @@"channel.allowFrom": "Allowed Users","channel.allowFromAdd": "Add user","channel.allowFromEmpty": "No users added yet — anyone can interact with the bot.",- "channel.allowFromHint": "Only listed users can interact with the bot; your 'Platform User ID' is auto-included.",+ "channel.allowFromHint": "Only listed users can interact with the bot in DMs, groups, and Guest Mode; your 'Platform User ID' is auto-included.","channel.allowFromIdLabel": "User ID","channel.allowFromIdPlaceholder": "Platform user ID","channel.allowFromNameLabel": "Note",@@ -107,6 +107,16 @@"channel.groupPolicyHint": "Where the bot responds in groups, channels, and threads","channel.groupPolicyOpen": "Open","channel.groupPolicyOpenHint": "Respond in any group, channel, or thread",+ "channel.guestPolicy": "Guest Policy",+ "channel.guestPolicyAllowlist": "Allowlist",+ "channel.guestPolicyAllowlistHint": "Only listed users can use Guest Mode",+ "channel.guestPolicyDisabled": "Disabled",+ "channel.guestPolicyDisabledHint": "Reject all Guest Mode summons",+ "channel.guestPolicyHint": "Who can summon the bot through Telegram Guest Mode",+ "channel.guestPolicyOpen": "Open",+ "channel.guestPolicyOpenHint": "Accept Guest Mode summons from anyone",+ "channel.guestPolicyPairing": "Pairing",+ "channel.guestPolicyPairingHint": "Strangers need /approve to use Guest Mode","channel.historyLimit": "History Message Limit","channel.historyLimitHint": "Default number of messages to fetch when reading channel history","channel.home.title": "Chat with <avatar/>{{name}} on Your Favorite App",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 9c15f459d7d..dac9c21b98c 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -2,7 +2,7 @@"channel.allowFrom": "允许的用户","channel.allowFromAdd": "添加用户","channel.allowFromEmpty": "尚未添加任何用户——任何人都可以与机器人交互。",- "channel.allowFromHint": "仅列表内用户可与机器人交互,「你的平台用户 ID」会自动加入。",+ "channel.allowFromHint": "仅列表内用户可通过私信、群组和访客模式与机器人交互,「你的平台用户 ID」会自动加入。","channel.allowFromIdLabel": "用户 ID","channel.allowFromIdPlaceholder": "平台用户 ID","channel.allowFromNameLabel": "备注",@@ -107,6 +107,16 @@"channel.groupPolicyHint": "机器人在群组、频道、子话题中的响应范围","channel.groupPolicyOpen": "开放","channel.groupPolicyOpenHint": "在所有群组、频道、子话题中响应",+ "channel.guestPolicy": "访客模式策略",+ "channel.guestPolicyAllowlist": "白名单",+ "channel.guestPolicyAllowlistHint": "仅允许名单内的用户使用访客模式",+ "channel.guestPolicyDisabled": "禁用",+ "channel.guestPolicyDisabledHint": "拒绝所有访客模式召唤",+ "channel.guestPolicyHint": "谁可以通过 Telegram 访客模式召唤机器人",+ "channel.guestPolicyOpen": "开放",+ "channel.guestPolicyOpenHint": "接受任何人的访客模式召唤",+ "channel.guestPolicyPairing": "配对审批",+ "channel.guestPolicyPairingHint": "陌生人需经 /approve 审批后才能使用访客模式","channel.historyLimit": "历史消息条数","channel.historyLimitHint": "读取频道历史消息时默认获取的消息数量","channel.home.title": "在你喜爱的应用中与 <avatar/>{{name}} 聊天",diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex d07eea2bd90..146412b3053 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -289,9 +289,19 @@ export default {'channel.dmPolicyOpenHint': 'Accept DMs from anyone','channel.dmPolicyPairing': 'Pairing','channel.dmPolicyPairingHint': 'Strangers need /approve to DM',+ 'channel.guestPolicy': 'Guest Policy',+ 'channel.guestPolicyHint': 'Who can summon the bot through Telegram Guest Mode',+ 'channel.guestPolicyAllowlist': 'Allowlist',+ 'channel.guestPolicyAllowlistHint': 'Only listed users can use Guest Mode',+ 'channel.guestPolicyDisabled': 'Disabled',+ 'channel.guestPolicyDisabledHint': 'Reject all Guest Mode summons',+ 'channel.guestPolicyOpen': 'Open',+ 'channel.guestPolicyOpenHint': 'Accept Guest Mode summons from anyone',+ 'channel.guestPolicyPairing': 'Pairing',+ 'channel.guestPolicyPairingHint': 'Strangers need /approve to use Guest Mode','channel.allowFrom': 'Allowed Users','channel.allowFromHint':- "Only listed users can interact with the bot; your 'Platform User ID' is auto-included.",+ "Only listed users can interact with the bot in DMs, groups, and Guest Mode; your 'Platform User ID' is auto-included.",'channel.allowFromIdLabel': 'User ID','channel.allowFromIdPlaceholder': 'Platform user ID','channel.allowFromNameLabel': 'Note',