Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(messenger): route iMessage / SMS through a shared Linq number pool (#20367)

Arvin Xu0b064e7ce63f
diff --git a/apps/cli/src/commands/botMessengers.test.ts b/apps/cli/src/commands/botMessengers.test.ts
index 4a59ed7b30f..1d329a420ab 100644
--- a/apps/cli/src/commands/botMessengers.test.ts
+++ b/apps/cli/src/commands/botMessengers.test.ts
@@ -313,6 +313,26 @@ describe('bot messengers', () => {
});
});
+ it('accepts Linq (iMessage / SMS) as a link-management platform', async () => {
+ mockTrpcClient.messenger.setActiveAgent.mutate.mockResolvedValueOnce({ success: true });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'links',
+ 'set-agent',
+ 'linq',
+ '--agent',
+ 'agent_sms',
+ ]);
+ expect(mockTrpcClient.messenger.setActiveAgent.mutate).toHaveBeenCalledWith({
+ agentId: 'agent_sms',
+ platform: 'linq',
+ tenantId: undefined,
+ });
+ });
+
it('passes agentId through to setActiveAgent', async () => {
mockTrpcClient.messenger.setActiveAgent.mutate.mockResolvedValueOnce({ success: true });
await createProgram().parseAsync([
diff --git a/apps/cli/src/commands/botMessengers.ts b/apps/cli/src/commands/botMessengers.ts
index 8503008069f..44b846bb616 100644
--- a/apps/cli/src/commands/botMessengers.ts
+++ b/apps/cli/src/commands/botMessengers.ts
@@ -20,7 +20,7 @@ import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable } from '../utils/format';
-const PLATFORMS = ['telegram', 'slack', 'discord', 'wechat'] as const;
+const PLATFORMS = ['telegram', 'slack', 'discord', 'wechat', 'linq'] as const;
type MessengerPlatform = (typeof PLATFORMS)[number];
const validatePlatform = (value: string): MessengerPlatform => {
diff --git a/apps/server/src/routers/lambda/messenger.ts b/apps/server/src/routers/lambda/messenger.ts
index 6e6ab20ace2..358e83baa8a 100644
--- a/apps/server/src/routers/lambda/messenger.ts
+++ b/apps/server/src/routers/lambda/messenger.ts
@@ -1,3 +1,4 @@
+import { buildLinqDeepLink, createLinqLinkCode } from '@lobechat/agent-address-linq';
import { MESSENGER_PUSH_CONTENT_MAX_LENGTH } from '@lobechat/builtin-tool-message';
import { fetchQrCode, pollQrStatus } from '@lobechat/chat-adapter-wechat';
import { INBOX_SESSION_ID } from '@lobechat/const';
@@ -13,6 +14,7 @@ import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPer
import {
getEnabledMessengerPlatforms,
getMessengerDiscordConfig,
+ getMessengerLinqConfig,
getMessengerSlackConfig,
getMessengerTelegramConfig,
isMessengerPlatformEnabled,
@@ -64,6 +66,8 @@ import {
releaseWechatQrFinalizeLock,
} from '@/server/services/messenger';
import { wechatInstallationKey } from '@/server/services/messenger/installations';
+import { issueLinkCode, peekLinkCodeStatus } from '@/server/services/messenger/linkTokenStore';
+import { pickLinqPoolNumber } from '@/server/services/messenger/platforms/linq/pool';
import {
getMessengerPushWindow,
MESSENGER_PUSH_PLATFORMS,
@@ -75,6 +79,7 @@ const platformEnum = z.enum([
'slack',
'discord',
'wechat',
+ 'linq',
]) satisfies z.ZodType<MessengerPlatform>;
const REVOKED_SLACK_AUTH_ERRORS = new Set([
@@ -553,6 +558,69 @@ export const messengerRouter = router({
}
}),
+ /**
+ * Start an iMessage / SMS link on the shared Linq pool. The signed-in user
+ * gets a one-time code plus `sms:` / `imessage:` deep links prefilled with
+ * it; texting that code from their phone to the pool is what binds the
+ * sender's handle to this account (see `MessengerLinqBinder`). The pool
+ * number is only a destination — any number in the pool would route the
+ * same way, because inbound is matched by sender, never by number.
+ */
+ createLinqLink: messengerProcedure.mutation(async ({ ctx }) => {
+ const config = await getMessengerLinqConfig();
+ if (!config) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'messenger.error.platformNotConfigured',
+ });
+ }
+ await assertBotFeatureAccess({ action: 'manage', platform: 'linq', userId: ctx.userId });
+
+ const existing = await ctx.messengerLinkModel.findByPlatform('linq', '');
+ if (existing) {
+ throw new TRPCError({ code: 'CONFLICT', message: 'verify.error.unlinkBeforeRelink' });
+ }
+
+ // Same default as a first WeChat scan: land on the personal inbox agent so
+ // the first message after linking already has somewhere to go.
+ const activeAgentId = (await ctx.getAgentModel().getBuiltinAgent(INBOX_SESSION_ID))?.id ?? null;
+ const workspaceId = activeAgentId
+ ? (await resolveAuthorizedAgentScope(ctx.serverDB, ctx.userId, activeAgentId)).workspaceId
+ : null;
+
+ const { code, expiresAt, pollId } = await issueLinkCode({
+ activeAgentId,
+ mintCode: createLinqLinkCode,
+ platform: 'linq',
+ userId: ctx.userId,
+ workspaceId,
+ });
+
+ const deepLink = buildLinqDeepLink({
+ code,
+ number: pickLinqPoolNumber(config.numbers, ctx.userId),
+ });
+ if (!deepLink) {
+ throw new TRPCError({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'messenger.error.platformNotConfigured',
+ });
+ }
+
+ return { code, deepLink, expiresAt, pollId };
+ }),
+
+ /** Poll a Linq link started by `createLinqLink` until the code arrives. */
+ pollLinqLink: messengerProcedure
+ .input(z.object({ pollId: z.string().min(8) }))
+ .query(async ({ ctx, input }) => {
+ const result = await peekLinkCodeStatus(input.pollId, ctx.userId);
+ if (result.status !== 'linked') return result;
+
+ const link = await ctx.messengerLinkModel.findByPlatform('linq', '');
+ return { ...result, link: link ?? null };
+ }),
+
/**
* Public peek used by the verify-im page to render the IM identity preview
* before the user confirms. Does NOT consume the token.
diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.ts
index de5961b0886..93083b3a6fe 100644
--- a/apps/server/src/services/bot/AgentBridgeService.ts
+++ b/apps/server/src/services/bot/AgentBridgeService.ts
@@ -15,6 +15,7 @@ import { AiAgentService } from '@/server/services/aiAgent';
import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
import { GatewayService } from '@/server/services/gateway';
import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewayClient';
+import { messengerPlatformRegistry } from '@/server/services/messenger/platforms';
import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
import { SystemAgentService } from '@/server/services/systemAgent';
@@ -853,9 +854,12 @@ export class AgentBridgeService {
trigger?: string;
},
): Promise<{ reply: string; topicId: string }> {
- // Resolve bot platform context from platform registry
+ // Resolve bot platform context from platform registry. Messenger-only
+ // platforms (Linq) have no bot-channel definition and carry the same reply
+ // traits on their messenger definition instead.
const platformDef = opts.botContext?.platform
- ? platformRegistry.getPlatform(opts.botContext.platform)
+ ? (platformRegistry.getPlatform(opts.botContext.platform) ??
+ messengerPlatformRegistry.getPlatform(opts.botContext.platform))
: undefined;
// 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
diff --git a/apps/server/src/services/bot/BotCallbackService.ts b/apps/server/src/services/bot/BotCallbackService.ts
index 5555ab16333..7132138a3d0 100644
--- a/apps/server/src/services/bot/BotCallbackService.ts
+++ b/apps/server/src/services/bot/BotCallbackService.ts
@@ -181,7 +181,8 @@ export class BotCallbackService {
workspaceId: body.workspaceId,
});
- const entry = platformRegistry.getPlatform(platform);
+ const entry =
+ platformRegistry.getPlatform(platform) ?? messengerPlatformRegistry.getPlatform(platform);
const canEdit = entry?.supportsMessageEdit !== false;
const replyLocale = getBotReplyLocale(platform);
const reactionMode = normalizeBotReactionMode(settings.reactionMode);
diff --git a/apps/server/src/services/bot/platforms/const.ts b/apps/server/src/services/bot/platforms/const.ts
index 308d2a71667..afa830d6248 100644
--- a/apps/server/src/services/bot/platforms/const.ts
+++ b/apps/server/src/services/bot/platforms/const.ts
@@ -89,6 +89,7 @@ const PLATFORM_REPLY_LOCALES: Record<string, BotReplyLocale> = {
feishu: 'zh-CN',
imessage: 'en-US',
lark: 'en-US',
+ linq: 'en-US',
qq: 'zh-CN',
slack: 'en-US',
telegram: 'en-US',
diff --git a/apps/server/src/services/bot/platforms/messageCapabilities.test.ts b/apps/server/src/services/bot/platforms/messageCapabilities.test.ts
index aa91c08864a..cdcfb52d80f 100644
--- a/apps/server/src/services/bot/platforms/messageCapabilities.test.ts
+++ b/apps/server/src/services/bot/platforms/messageCapabilities.test.ts
@@ -60,7 +60,9 @@ describe('PLATFORM_UNSUPPORTED_MESSAGE_APIS', () => {
.filter(([, apis]) => apis.includes('readMessages'))
.map(([id]) => id)
.sort();
- expect(noHistory).toEqual(['qq', 'telegram', 'wechat']);
+ // `linq` is messenger-only (shared iMessage / SMS pool): it has no channel
+ // service behind the message tool at all, so history is pre-injected.
+ expect(noHistory).toEqual(['linq', 'qq', 'telegram', 'wechat']);
});
});
diff --git a/apps/server/src/services/bot/platforms/messageCapabilities.ts b/apps/server/src/services/bot/platforms/messageCapabilities.ts
index 4ebbb516e71..1608eb9b512 100644
--- a/apps/server/src/services/bot/platforms/messageCapabilities.ts
+++ b/apps/server/src/services/bot/platforms/messageCapabilities.ts
@@ -85,6 +85,9 @@ export const PLATFORM_UNSUPPORTED_MESSAGE_APIS: Record<string, string[]> = {
MessageApiName.sendDirectMessage,
MessageApiName.unpinMessage,
],
+ // The shared Linq pool (messenger iMessage / SMS) has no channel API behind
+ // the message tool — replies flow through the messenger, nothing else.
+ linq: [...CHANNEL_MESSAGE_APIS],
// Lark shares Feishu's service, so it has the same limitations.
lark: [
MessageApiName.createPoll,
diff --git a/apps/server/src/services/messenger/MessengerRouter.test.ts b/apps/server/src/services/messenger/MessengerRouter.test.ts
index d6b5925fdb3..871d5296540 100644
--- a/apps/server/src/services/messenger/MessengerRouter.test.ts
+++ b/apps/server/src/services/messenger/MessengerRouter.test.ts
@@ -260,6 +260,18 @@ vi.mock('./platforms/wechat/binder', () => ({
}),
}));
+vi.mock('./platforms/linq/binder', () => ({
+ MessengerLinqBinder: vi.fn(function () {
+ return { createClient: vi.fn(), handleUnlinkedMessage: vi.fn(), sendDmText: vi.fn() };
+ }),
+}));
+
+const mockLinqGate = vi.hoisted(() => ({
+ preprocess: vi.fn(async (): Promise<Response | null> => null),
+ settle: vi.fn(async () => {}),
+}));
+vi.mock('./platforms/linq/webhook', () => ({ linqWebhookGate: mockLinqGate }));
+
const buildSlackRequest = (body: string, headers: Record<string, string> = {}): Request =>
new Request('https://app.example.com/api/agent/messenger/webhooks/slack', {
body,
@@ -356,6 +368,26 @@ afterEach(() => {
});
describe('MessengerRouter.getWebhookHandler', () => {
+ it('lets the gate settle a delivery whose handling failed', async () => {
+ mockResolveByPayload.mockResolvedValueOnce(null);
+ const router = new MessengerRouter();
+ const req = new Request('https://e.com/x', { body: '{}', method: 'POST' });
+
+ const res = await router.getWebhookHandler('linq')(req);
+
+ expect(res.status).toBe(404);
+ expect(mockLinqGate.settle).toHaveBeenCalledWith(req, res);
+ });
+
+ it('lets the gate settle a delivery whose handling threw', async () => {
+ mockResolveByPayload.mockRejectedValueOnce(new Error('db down'));
+ const router = new MessengerRouter();
+ const req = new Request('https://e.com/x', { body: '{}', method: 'POST' });
+
+ await expect(router.getWebhookHandler('linq')(req)).rejects.toThrow('db down');
+ expect(mockLinqGate.settle).toHaveBeenCalledWith(req, undefined);
+ });
+
it('rejects unknown platforms with 404', async () => {
const router = new MessengerRouter();
const handler = router.getWebhookHandler('discord');
@@ -1026,6 +1058,24 @@ describe('MessengerRouter DM dispatch (regression)', () => {
expect(mockHandleMention).not.toHaveBeenCalled();
});
+ it('replies with an error instead of dropping the message when the link lookup fails', async () => {
+ // Handlers run after the webhook was acknowledged, so the platform never
+ // redelivers; a failure here has to reach the sender as a reply.
+ await loadSlackBot();
+ mockFindLink.mockRejectedValueOnce(new Error('db down'));
+
+ const handler = mockChatBot.onNewMention.mock.calls[0][0] as (
+ thread: any,
+ msg: any,
+ ) => Promise<void>;
+ const thread = fakeDmThread();
+ await expect(handler(thread, fakeMessage({ isMention: true }))).resolves.toBeUndefined();
+
+ expect(thread.post).toHaveBeenCalledTimes(1);
+ expect(mockSlackBinder.handleUnlinkedMessage).not.toHaveBeenCalled();
+ expect(mockHandleMention).not.toHaveBeenCalled();
+ });
+
it('routes an unlinked first-touch DM through handleUnlinkedMessage WITHOUT channelMentionThreadId', async () => {
await loadSlackBot();
mockFindLink.mockResolvedValue(null);
diff --git a/apps/server/src/services/messenger/MessengerRouter.ts b/apps/server/src/services/messenger/MessengerRouter.ts
index 2de2daf4651..9827fa16058 100644
--- a/apps/server/src/services/messenger/MessengerRouter.ts
+++ b/apps/server/src/services/messenger/MessengerRouter.ts
@@ -43,7 +43,7 @@ import { isResourceAuthorOrAdmin } from '@/server/services/resourcePermission';
import { getInstallationStore } from './installations';
import type { InstallationCredentials } from './installations/types';
-import { messengerPlatformRegistry } from './platforms';
+import { type MessengerPlatformDefinition, messengerPlatformRegistry } from './platforms';
import { getMessengerSystemStrings } from './systemReply';
import type {
AgentPickerEntry,
@@ -306,60 +306,84 @@ export class MessengerRouter {
if (early) return early;
}
- // ----- Resolve install + lazy-load bot -------------------------------
- const store = getInstallationStore(definition.id);
- if (!store) {
- return new Response(`Messenger ${platform} has no installation store`, { status: 500 });
+ // The gate may have claimed this delivery (Linq replay dedupe); let it
+ // settle that claim once the outcome is known so a failed delivery
+ // stays retryable instead of being answered as a duplicate forever.
+ let response: Response | undefined;
+ try {
+ response = await this.dispatchVerifiedWebhook(definition, req, rawBody, options);
+ return response;
+ } finally {
+ if (definition.webhookGate?.settle) {
+ await definition.webhookGate.settle(req, response).catch((error: unknown) => {
+ log('webhook: gate settle failed for %s: %O', platform, error);
+ });
+ }
}
+ };
+ }
- const creds = await store.resolveByPayload(reconstructRequest(req, rawBody), rawBody);
- if (!creds) {
- log('webhook: no install resolved for platform=%s', platform);
- return new Response('install not found', { status: 404 });
- }
+ private async dispatchVerifiedWebhook(
+ definition: MessengerPlatformDefinition,
+ req: Request,
+ rawBody: string,
+ options?: WebhookOptions,
+ ): Promise<Response> {
+ const platform = definition.id;
+
+ // ----- Resolve install + lazy-load bot -------------------------------
+ const store = getInstallationStore(definition.id);
+ if (!store) {
+ return new Response(`Messenger ${platform} has no installation store`, { status: 500 });
+ }
- const bot = await this.getOrCreateBot(creds);
- if (!bot) {
- return new Response(`Messenger ${platform} bot unavailable`, { status: 503 });
- }
+ const creds = await store.resolveByPayload(reconstructRequest(req, rawBody), rawBody);
+ if (!creds) {
+ log('webhook: no install resolved for platform=%s', platform);
+ return new Response('install not found', { status: 404 });
+ }
- // ----- App Home `Messages` tab opener (Slack marketplace welcome) ---
- // Slack requires a welcome message the first time a user opens the
- // Messages tab. chat-sdk's slack adapter drops these events, so peek
- // the raw body here and dispatch via the binder. Dedupe is handled
- // inside `handleAppHomeOpened` so a per-user welcome fires once.
- if (bot.binder.extractAppHomeOpened) {
- try {
- const opener = await bot.binder.extractAppHomeOpened(reconstructRequest(req, rawBody));
- if (opener) {
- await this.handleAppHomeOpened(bot, creds, opener);
- return new Response('OK', { status: 200 });
- }
- } catch (error) {
- log('extractAppHomeOpened failed for %s: %O', platform, error);
+ const bot = await this.getOrCreateBot(creds);
+ if (!bot) {
+ return new Response(`Messenger ${platform} bot unavailable`, { status: 503 });
+ }
+
+ // ----- App Home `Messages` tab opener (Slack marketplace welcome) ---
+ // Slack requires a welcome message the first time a user opens the
+ // Messages tab. chat-sdk's slack adapter drops these events, so peek
+ // the raw body here and dispatch via the binder. Dedupe is handled
+ // inside `handleAppHomeOpened` so a per-user welcome fires once.
+ if (bot.binder.extractAppHomeOpened) {
+ try {
+ const opener = await bot.binder.extractAppHomeOpened(reconstructRequest(req, rawBody));
+ if (opener) {
+ await this.handleAppHomeOpened(bot, creds, opener);
+ return new Response('OK', { status: 200 });
}
+ } catch (error) {
+ log('extractAppHomeOpened failed for %s: %O', platform, error);
}
+ }
- // ----- Tap-action callbacks (binder peeks raw body) -----------------
- if (bot.binder.extractCallbackAction) {
- try {
- const action = await bot.binder.extractCallbackAction(reconstructRequest(req, rawBody));
- if (action) {
- await this.handleCallbackAction(bot.binder, creds, action, bot.chatBot);
- return new Response('OK', { status: 200 });
- }
- } catch (error) {
- log('extractCallbackAction failed for %s: %O', platform, error);
+ // ----- Tap-action callbacks (binder peeks raw body) -----------------
+ if (bot.binder.extractCallbackAction) {
+ try {
+ const action = await bot.binder.extractCallbackAction(reconstructRequest(req, rawBody));
+ if (action) {
+ await this.handleCallbackAction(bot.binder, creds, action, bot.chatBot);
+ return new Response('OK', { status: 200 });
}
+ } catch (error) {
+ log('extractCallbackAction failed for %s: %O', platform, error);
}
+ }
- // ----- Normal message → chat-sdk handler ----------------------------
- const handler = (bot.chatBot.webhooks as any)?.[platform];
- if (!handler) {
- return new Response(`Messenger ${platform} webhook unavailable`, { status: 500 });
- }
- return handler(reconstructRequest(req, rawBody), options);
- };
+ // ----- Normal message → chat-sdk handler ----------------------------
+ const handler = (bot.chatBot.webhooks as any)?.[platform];
+ if (!handler) {
+ return new Response(`Messenger ${platform} webhook unavailable`, { status: 500 });
+ }
+ return handler(reconstructRequest(req, rawBody), options);
}
// -------------------------------------------------------------------------
@@ -554,14 +578,19 @@ export class MessengerRouter {
}
return binder.sendDmText(chatId, text);
};
- const link = await MessengerAccountLinkModel.findByPlatformUser(
- serverDB,
- platform,
- senderId,
- tenantId,
- );
+ // Everything below runs after the webhook was already acknowledged
+ // (chat-sdk hands it to `waitUntil`), so the platform will not redeliver
+ // it. Any failure — including the link lookup — must therefore end in a
+ // reply the sender can act on (resend), never a silently dropped message.
try {
+ const link = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ platform,
+ senderId,
+ tenantId,
+ );
+
const parsed = parseCommand(message.text);
if (parsed) {
const command = commands.find((c) => c.name === parsed.name);
diff --git a/apps/server/src/services/messenger/installations/index.ts b/apps/server/src/services/messenger/installations/index.ts
index e1c65beb8bb..20868119726 100644
--- a/apps/server/src/services/messenger/installations/index.ts
+++ b/apps/server/src/services/messenger/installations/index.ts
@@ -2,6 +2,7 @@ import type { MessengerPlatform } from '@/config/messenger';
import type { ConnectionMode } from '../../bot/platforms';
import { DiscordInstallationStore } from './discord';
+import { LinqInstallationStore } from './linq';
import { SlackInstallationStore } from './slack';
import { TelegramInstallationStore } from './telegram';
import type { MessengerInstallationStore } from './types';
@@ -28,6 +29,9 @@ const create = (platform: MessengerPlatform): MessengerInstallationStore | null
case 'wechat': {
return new WechatInstallationStore();
}
+ case 'linq': {
+ return new LinqInstallationStore();
+ }
default: {
return null;
}
@@ -110,6 +114,7 @@ export const messengerConnectionIdForUser = (params: {
};
export { DISCORD_INSTALLATION_KEY, DiscordInstallationStore } from './discord';
+export { LINQ_INSTALLATION_KEY, LinqInstallationStore } from './linq';
export { SlackInstallationStore } from './slack';
export { TELEGRAM_INSTALLATION_KEY, TelegramInstallationStore } from './telegram';
export type { InstallationCredentials, MessengerInstallationStore } from './types';
diff --git a/apps/server/src/services/messenger/installations/linq.ts b/apps/server/src/services/messenger/installations/linq.ts
new file mode 100644
index 00000000000..0a4b9fd50ec
--- /dev/null
+++ b/apps/server/src/services/messenger/installations/linq.ts
@@ -0,0 +1,40 @@
+import debug from 'debug';
+
+import { getMessengerLinqConfig } from '@/config/messenger';
+
+import type { InstallationCredentials, MessengerInstallationStore } from './types';
+
+const log = debug('lobe-server:messenger:install-store:linq');
+
+/**
+ * The Linq pool is one deployment-level install: the same API key serves every
+ * pool number and every sender, so — like Telegram — there is no tenant.
+ * Routing happens per sender in `messenger_account_links`, not per install.
+ */
+export const LINQ_INSTALLATION_KEY = 'linq:singleton';
+
+const buildCreds = async (): Promise<InstallationCredentials | null> => {
+ const config = await getMessengerLinqConfig();
+ if (!config) return null;
+ return {
+ applicationId: LINQ_INSTALLATION_KEY,
+ botToken: config.apiKey,
+ installationKey: LINQ_INSTALLATION_KEY,
+ metadata: { poolSize: config.numbers.length },
+ platform: 'linq',
+ tenantId: '',
+ };
+};
+
+export class LinqInstallationStore implements MessengerInstallationStore {
+ async resolveByPayload(): Promise<InstallationCredentials | null> {
+ const creds = await buildCreds();
+ if (!creds) log('resolveByPayload: linq credentials not configured');
+ return creds;
+ }
+
+ async resolveByKey(installationKey: string): Promise<InstallationCredentials | null> {
+ if (installationKey !== LINQ_INSTALLATION_KEY) return null;
+ return buildCreds();
+ }
+}
diff --git a/apps/server/src/services/messenger/linkCodeStore.test.ts b/apps/server/src/services/messenger/linkCodeStore.test.ts
new file mode 100644
index 00000000000..eb4cb5fbe89
--- /dev/null
+++ b/apps/server/src/services/messenger/linkCodeStore.test.ts
@@ -0,0 +1,160 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ consumeLinkCode,
+ issueLinkCode,
+ peekLinkCodeStatus,
+ restoreLinkCode,
+ settleLinkCode,
+} from './linkTokenStore';
+
+vi.mock('@/config/messenger', () => ({
+ getMessengerLinkTokenTtl: vi.fn().mockReturnValue(1800),
+}));
+
+/** Minimal ioredis stand-in: values + per-key TTL, enough for the code store. */
+const fakeRedis = () => {
+ const store = new Map<string, string>();
+ const ttls = new Map<string, number>();
+ return {
+ client: {
+ del: vi.fn(async (key: string) => {
+ store.delete(key);
+ ttls.delete(key);
+ return 1;
+ }),
+ exists: vi.fn(async (key: string) => (store.has(key) ? 1 : 0)),
+ get: vi.fn(async (key: string) => store.get(key) ?? null),
+ getdel: vi.fn(async (key: string) => {
+ const value = store.get(key) ?? null;
+ store.delete(key);
+ return value;
+ }),
+ set: vi.fn(async (key: string, value: string, ...args: unknown[]) => {
+ if (args.includes('NX') && store.has(key)) return null;
+ store.set(key, value);
+ const exIndex = args.indexOf('EX');
+ if (exIndex !== -1) ttls.set(key, args[exIndex + 1] as number);
+ return 'OK';
+ }),
+ ttl: vi.fn(async (key: string) => (store.has(key) ? (ttls.get(key) ?? -1) : -2)),
+ },
+ store,
+ };
+};
+
+let redisRef: ReturnType<typeof fakeRedis>;
+
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: vi.fn(() => redisRef.client),
+}));
+
+let seq = 0;
+const mintCode = () => `LH-TESTCOD${++seq}`;
+
+const issue = (userId = 'user_alice') =>
+ issueLinkCode({
+ activeAgentId: 'agt_inbox',
+ mintCode,
+ platform: 'linq',
+ userId,
+ workspaceId: null,
+ });
+
+beforeEach(() => {
+ redisRef = fakeRedis();
+ seq = 0;
+});
+
+describe('link codes', () => {
+ it('issues a code, then hands it to exactly one consumer', async () => {
+ const { code, pollId } = await issue();
+
+ const first = await consumeLinkCode(code, 'linq');
+ expect(first).toMatchObject({
+ activeAgentId: 'agt_inbox',
+ platform: 'linq',
+ pollId,
+ userId: 'user_alice',
+ });
+
+ // A replayed webhook, or a second phone sending the same code, gets nothing.
+ expect(await consumeLinkCode(code, 'linq')).toBeNull();
+ });
+
+ it('matches a code typed in lower case', async () => {
+ const { code } = await issue();
+ expect(await consumeLinkCode(code.toLowerCase(), 'linq')).not.toBeNull();
+ });
+
+ it('reuses the live code for the same user instead of invalidating it', async () => {
+ const first = await issue();
+ const second = await issue();
+ expect(second.code).toBe(first.code);
+ expect(second.pollId).toBe(first.pollId);
+
+ const other = await issue('user_bob');
+ expect(other.code).not.toBe(first.code);
+ });
+
+ it('refuses a code issued for another platform', async () => {
+ const { code } = await issue();
+ expect(await consumeLinkCode(code, 'telegram')).toBeNull();
+ });
+
+ it('reports pending → linked to the issuing user only', async () => {
+ const { code, pollId } = await issue();
+ expect(await peekLinkCodeStatus(pollId, 'user_alice')).toEqual({ status: 'pending' });
+
+ await consumeLinkCode(code, 'linq');
+ await settleLinkCode(pollId, {
+ linkedAt: 1,
+ platformUserId: '+15550001111',
+ status: 'linked',
+ });
+
+ expect(await peekLinkCodeStatus(pollId, 'user_alice')).toEqual({
+ linkedAt: 1,
+ platformUserId: '+15550001111',
+ status: 'linked',
+ });
+ // Someone else's poll id reveals nothing.
+ expect(await peekLinkCodeStatus(pollId, 'user_bob')).toEqual({ status: 'expired' });
+ });
+
+ it('reports expired once a pending code is gone', async () => {
+ const { code, pollId } = await issue();
+ redisRef.store.delete(`messenger:link-code:${code}`);
+ expect(await peekLinkCodeStatus(pollId, 'user_alice')).toEqual({ status: 'expired' });
+ });
+
+ it('surfaces a failed link outcome to the polling page', async () => {
+ const { pollId } = await issue();
+ await settleLinkCode(pollId, { reason: 'already_linked_to_other', status: 'failed' });
+ expect(await peekLinkCodeStatus(pollId, 'user_alice')).toEqual({
+ reason: 'already_linked_to_other',
+ status: 'failed',
+ });
+ });
+
+ it('restores a consumed code so the same code links on a resend', async () => {
+ const { code, pollId } = await issue();
+ const payload = (await consumeLinkCode(code, 'linq'))!;
+ expect(await consumeLinkCode(code, 'linq')).toBeNull();
+
+ await restoreLinkCode(code, payload);
+
+ expect(await peekLinkCodeStatus(pollId, 'user_alice')).toEqual({ status: 'pending' });
+ expect(await consumeLinkCode(code, 'linq')).toMatchObject({ pollId, userId: 'user_alice' });
+ });
+
+ it('leaves an already-expired code gone', async () => {
+ const { code } = await issue();
+ const payload = (await consumeLinkCode(code, 'linq'))!;
+
+ await restoreLinkCode(code, { ...payload, createdAt: Date.now() - 3600 * 1000 });
+
+ expect(await consumeLinkCode(code, 'linq')).toBeNull();
+ });
+});
diff --git a/apps/server/src/services/messenger/linkTokenStore.ts b/apps/server/src/services/messenger/linkTokenStore.ts
index 37462b1d1c2..7f92537e724 100644
--- a/apps/server/src/services/messenger/linkTokenStore.ts
+++ b/apps/server/src/services/messenger/linkTokenStore.ts
@@ -161,3 +161,224 @@ export const peekConsumedLinkToken = async (
return null;
}
};
+
+// ---------------------------------------------------------------------------
+// Web-initiated link codes.
+//
+// The link token above is minted by the IM side (the bot learns a platform
+// user id first, the web page binds it). Carrier platforms (Linq iMessage /
+// SMS) run the other way round: the signed-in web user asks for a code, then
+// texts it from their phone to a shared pool number. The inbound sender is the
+// identity being linked, so the code has to remember the LobeHub side instead.
+// ---------------------------------------------------------------------------
+
+/** One-time code a person sends from the IM side, e.g. `LH-7Q2M4XKP`. */
+export type LinkCode = string;
+
+export interface LinkCodePayload {
+ /** Agent the first inbound message lands on once the link exists. */
+ activeAgentId: string | null;
+ createdAt: number;
+ platform: MessengerPlatform;
+ /** Opaque id the web page polls; never reveals the code itself. */
+ pollId: string;
+ userId: string;
+ workspaceId: string | null;
+}
+
+export type LinkCodePollStatus =
+ | { status: 'pending' }
+ | { linkedAt: number; platformUserId: string; status: 'linked' }
+ | { reason: 'already_linked_to_other' | 'unlink_before_relink'; status: 'failed' };
+
+interface LinkCodePollRecord {
+ code: LinkCode;
+ platform: MessengerPlatform;
+ result: LinkCodePollStatus;
+ userId: string;
+}
+
+const linkCodeKey = (code: LinkCode): string => `messenger:link-code:${code.toUpperCase()}`;
+const linkCodeReuseKey = (platform: MessengerPlatform, userId: string): string =>
+ `messenger:link-code-reuse:${platform}:${userId}`;
+const linkCodePollKey = (pollId: string): string => `messenger:link-code-poll:${pollId}`;
+
+const requireRedis = () => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) throw new Error('Redis is required for messenger link code storage');
+ return redis;
+};
+
+/**
+ * Issue (or reuse) a link code for a signed-in user. `mintCode` is injected so
+ * each platform keeps its own code format — Linq codes are `LH-` prefixed so
+ * they survive being embedded in an arbitrary message body.
+ *
+ * A live code for the same `(platform, userId)` is returned again with its
+ * remaining TTL, so reopening the connect page does not invalidate the link
+ * the person may already have sent from their phone.
+ */
+export const issueLinkCode = async (
+ params: Omit<LinkCodePayload, 'createdAt' | 'pollId'> & { mintCode: () => LinkCode },
+): Promise<{ code: LinkCode; expiresAt: number; pollId: string }> => {
+ const redis = requireRedis();
+ const { mintCode, ...payload } = params;
+
+ const existing = await redis.get(linkCodeReuseKey(payload.platform, payload.userId));
+ if (existing) {
+ const raw = await redis.get(linkCodeKey(existing));
+ const ttl = raw ? await redis.ttl(linkCodeKey(existing)) : -2;
+ if (raw && ttl > 0) {
+ try {
+ const live = JSON.parse(raw) as LinkCodePayload;
+ // Re-pin the agent the user just picked; the code itself stays.
+ const updated: LinkCodePayload = {
+ ...live,
+ activeAgentId: payload.activeAgentId,
+ workspaceId: payload.workspaceId,
+ };
+ await redis.set(linkCodeKey(existing), JSON.stringify(updated), 'EX', ttl);
+ return { code: existing, expiresAt: Date.now() + ttl * 1000, pollId: live.pollId };
+ } catch {
+ // Corrupt entry — fall through and mint a fresh one.
+ }
+ }
+ }
+
+ const ttl = getMessengerLinkTokenTtl();
+ const code = mintCode().toUpperCase();
+ const pollId = randomUUID().replaceAll('-', '');
+ const value: LinkCodePayload = { ...payload, createdAt: Date.now(), pollId };
+ const poll: LinkCodePollRecord = {
+ code,
+ platform: payload.platform,
+ result: { status: 'pending' },
+ userId: payload.userId,
+ };
+
+ // NX: a collision with a live code is astronomically unlikely, but it must
+ // never silently hand someone else's pending code a new owner.
+ const created = await redis.set(linkCodeKey(code), JSON.stringify(value), 'EX', ttl, 'NX');
+ if (created !== 'OK') throw new Error('Link code collision, retry');
+ await redis.set(linkCodeReuseKey(payload.platform, payload.userId), code, 'EX', ttl);
+ // The poll record outlives the code so a page polling right at expiry still
+ // sees the `linked` outcome instead of a misleading `expired`.
+ await redis.set(
+ linkCodePollKey(pollId),
+ JSON.stringify(poll),
+ 'EX',
+ ttl + CONSUMED_MARKER_TTL_SECONDS,
+ );
+
+ log('issueLinkCode: issued %s code for user=%s ttl=%ds', payload.platform, payload.userId, ttl);
+ return { code, expiresAt: Date.now() + ttl * 1000, pollId };
+};
+
+/**
+ * Atomically take a link code. Only the first inbound carrying the code gets
+ * the payload; a replay (or a second phone sending the same code) gets null.
+ * Codes are platform-scoped so a Linq code cannot bind a Telegram identity.
+ */
+export const consumeLinkCode = async (
+ code: LinkCode,
+ platform: MessengerPlatform,
+): Promise<LinkCodePayload | null> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return null;
+
+ const raw = await redis.getdel(linkCodeKey(code));
+ if (!raw) return null;
+
+ let payload: LinkCodePayload;
+ try {
+ payload = JSON.parse(raw) as LinkCodePayload;
+ } catch {
+ return null;
+ }
+ if (payload.platform !== platform) {
+ log('consumeLinkCode: platform mismatch code=%s expected=%s', payload.platform, platform);
+ return null;
+ }
+
+ await redis.del(linkCodeReuseKey(payload.platform, payload.userId));
+ return payload;
+};
+
+/** Record the outcome of a consumed code so the polling web page can settle. */
+export const settleLinkCode = async (
+ pollId: string,
+ result: Exclude<LinkCodePollStatus, { status: 'pending' }>,
+): Promise<void> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return;
+
+ const key = linkCodePollKey(pollId);
+ const raw = await redis.get(key);
+ if (!raw) return;
+ try {
+ const record = JSON.parse(raw) as LinkCodePollRecord;
+ await redis.set(key, JSON.stringify({ ...record, result }), 'EX', CONSUMED_MARKER_TTL_SECONDS);
+ } catch {
+ /* corrupt record — the page falls back to `expired` */
+ }
+};
+
+/**
+ * Read a poll record for its owner. Returns `expired` when the record is gone,
+ * belongs to someone else, or the code ran out while still pending.
+ */
+export const peekLinkCodeStatus = async (
+ pollId: string,
+ userId: string,
+): Promise<LinkCodePollStatus | { status: 'expired' }> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return { status: 'expired' };
+
+ const raw = await redis.get(linkCodePollKey(pollId));
+ if (!raw) return { status: 'expired' };
+
+ let record: LinkCodePollRecord;
+ try {
+ record = JSON.parse(raw) as LinkCodePollRecord;
+ } catch {
+ return { status: 'expired' };
+ }
+ if (record.userId !== userId) return { status: 'expired' };
+
+ if (record.result.status === 'pending' && !(await redis.exists(linkCodeKey(record.code)))) {
+ return { status: 'expired' };
+ }
+ return record.result;
+};
+
+/**
+ * Put a consumed code back after the bind it was consumed for failed for an
+ * unexpected reason (DB unreachable, …), so resending the same code works and
+ * the polling page stays `pending` instead of flipping to `expired`. Restores
+ * with whatever TTL the code had left; an already-expired code stays gone. NX
+ * keeps this from clobbering anything that claimed the key in the meantime.
+ */
+export const restoreLinkCode = async (code: LinkCode, payload: LinkCodePayload): Promise<void> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return;
+
+ const remaining =
+ getMessengerLinkTokenTtl() - Math.floor((Date.now() - payload.createdAt) / 1000);
+ if (remaining <= 0) return;
+
+ const restored = await redis.set(
+ linkCodeKey(code),
+ JSON.stringify(payload),
+ 'EX',
+ remaining,
+ 'NX',
+ );
+ if (restored !== 'OK') return;
+ await redis.set(
+ linkCodeReuseKey(payload.platform, payload.userId),
+ code.toUpperCase(),
+ 'EX',
+ remaining,
+ );
+ log('restoreLinkCode: restored %s code for user=%s', payload.platform, payload.userId);
+};
diff --git a/apps/server/src/services/messenger/outbound.ts b/apps/server/src/services/messenger/outbound.ts
index dc9da4309e5..22c59e59859 100644
--- a/apps/server/src/services/messenger/outbound.ts
+++ b/apps/server/src/services/messenger/outbound.ts
@@ -1,6 +1,8 @@
+import { markdownToPlainText } from '@lobechat/agent-address-linq';
import type { MessengerOversizeImageStrategy } from '@lobechat/const';
import debug from 'debug';
+import { getMessengerLinqConfig } from '@/config/messenger';
import {
PLATFORM_ATTACHMENT_BUDGETS,
prepareAttachmentsForBudget,
@@ -20,6 +22,8 @@ import { sendTelegramAttachments } from '@/server/services/bot/platforms/telegra
import type { BotMessageAttachment } from '@/server/services/bot/platforms/types';
import type { InstallationCredentials } from './installations/types';
+import { createLinqApi } from './platforms/linq/client';
+import { pickLinqPoolNumber } from './platforms/linq/pool';
const log = debug('lobe-messenger:outbound');
@@ -167,6 +171,29 @@ export const sendOutboundDirectMessage = async (params: {
for (const message of linkMessages) await api.postMessage(platformUserId, message);
return;
}
+ case 'linq': {
+ // Pool numbers are shared, so the "bot token" is the deployment API key
+ // and the handle picks the chat; `sendToHandle` reuses the person's
+ // existing thread with the pool before opening a new one.
+ const config = await getMessengerLinqConfig();
+ if (!config) throw new Error('Linq messenger is not configured');
+ const api = createLinqApi(config, pickLinqPoolNumber(config.numbers, platformUserId));
+ if (text) await api.sendToHandle({ handle: platformUserId, text: markdownToPlainText(text) });
+ for (const file of files ?? []) {
+ await api.sendToHandle({
+ attachment: {
+ data: file.data,
+ fetchUrl: file.fetchUrl,
+ mimeType: file.mimeType,
+ name: file.name,
+ },
+ handle: platformUserId,
+ });
+ }
+ for (const message of linkMessages)
+ await api.sendToHandle({ handle: platformUserId, text: message });
+ return;
+ }
default: {
// WeChat never reaches here — `sendMessengerPush` routes it to the
// windowed path before this point.
diff --git a/apps/server/src/services/messenger/platforms/index.ts b/apps/server/src/services/messenger/platforms/index.ts
index 7a3442e9a94..dee3de82196 100644
--- a/apps/server/src/services/messenger/platforms/index.ts
+++ b/apps/server/src/services/messenger/platforms/index.ts
@@ -1,10 +1,12 @@
import { discord } from './discord';
+import { linq } from './linq';
import { MessengerPlatformRegistry } from './registry';
import { slack } from './slack';
import { telegram } from './telegram';
import { wechat } from './wechat';
export { MessengerDiscordBinder } from './discord';
+export { linqWebhookGate, MessengerLinqBinder } from './linq';
export { MessengerPlatformRegistry } from './registry';
export { MessengerSlackBinder, slackWebhookGate } from './slack';
export { MessengerTelegramBinder } from './telegram';
@@ -24,4 +26,5 @@ export const messengerPlatformRegistry = new MessengerPlatformRegistry()
.register(slack)
.register(telegram)
.register(discord)
- .register(wechat);
+ .register(wechat)
+ .register(linq);
diff --git a/apps/server/src/services/messenger/platforms/linq/adapter.test.ts b/apps/server/src/services/messenger/platforms/linq/adapter.test.ts
new file mode 100644
index 00000000000..ec4aee0d427
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/adapter.test.ts
@@ -0,0 +1,113 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { LinqChatAdapter } from './adapter';
+import { pickLinqPoolNumber } from './pool';
+
+const makeAdapter = () => {
+ const api = {
+ sendText: vi.fn(async () => ({ chat_id: 'chat_1', message: { id: 'msg_out' } })),
+ startTyping: vi.fn(async () => {}),
+ };
+ const chat = {
+ getLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
+ getUserName: () => 'messenger-bot',
+ processMessage: vi.fn(),
+ };
+ const adapter = new LinqChatAdapter({ api: api as any });
+ return { adapter, api, chat };
+};
+
+const delivery = (data: Record<string, unknown>, eventType = 'message.received') =>
+ new Request('https://app.test/api/agent/messenger/webhooks/linq', {
+ body: JSON.stringify({ data, event_type: eventType }),
+ method: 'POST',
+ });
+
+const inbound = {
+ chat: { id: 'chat_1', is_group: false },
+ direction: 'inbound',
+ id: 'msg_in',
+ parts: [{ type: 'text', value: 'hello **there**' }],
+ sender_handle: { handle: '+1 (555) 000-1111' },
+ sent_at: '2026-10-05T00:00:00Z',
+};
+
+describe('LinqChatAdapter', () => {
+ it('turns a message.received delivery into a message authored by the normalized sender', async () => {
+ const { adapter, chat } = makeAdapter();
+ await adapter.initialize(chat as any);
+
+ const res = await adapter.handleWebhook(delivery(inbound));
+ expect(res.status).toBe(200);
+ expect(chat.processMessage).toHaveBeenCalledTimes(1);
+
+ const [, threadId, factory] = chat.processMessage.mock.calls[0];
+ expect(threadId).toBe('linq:chat_1');
+ const message = await factory();
+ // Routing key is the sender, normalized to E.164 — not the pool number.
+ expect(message.author.userId).toBe('+15550001111');
+ expect(message.text).toBe('hello **there**');
+ expect(message.threadId).toBe('linq:chat_1');
+ });
+
+ it.each([
+ ['outbound echoes', { ...inbound, direction: 'outbound' }, 'message.received'],
+ ['group chats', { ...inbound, chat: { id: 'chat_g', is_group: true } }, 'message.received'],
+ ['other event types', inbound, 'message.delivered'],
+ ['senders without a handle', { ...inbound, sender_handle: null }, 'message.received'],
+ ])('ignores %s', async (_label, data, eventType) => {
+ const { adapter, chat } = makeAdapter();
+ await adapter.initialize(chat as any);
+
+ const res = await adapter.handleWebhook(delivery(data, eventType));
+ expect(res.status).toBe(200);
+ expect(chat.processMessage).not.toHaveBeenCalled();
+ });
+
+ it('posts plain text into the chat, degrading markdown', async () => {
+ const { adapter, api, chat } = makeAdapter();
+ await adapter.initialize(chat as any);
+
+ const raw = await adapter.postMessage('linq:chat_1', { markdown: '**Done** — see `x`' });
+ expect(api.sendText).toHaveBeenCalledWith('chat_1', expect.not.stringContaining('**'));
+ expect(raw.id).toBe('msg_out');
+ });
+
+ it('keeps literal brackets and underscores instead of markdown-escaping them', async () => {
+ const { adapter, api, chat } = makeAdapter();
+ await adapter.initialize(chat as any);
+
+ await adapter.postMessage('linq:chat_1', { markdown: '[note] see snake_case and a*b' });
+ expect(api.sendText).toHaveBeenCalledWith('chat_1', '[note] see snake_case and a*b');
+ });
+
+ it('never re-sends on edit (iMessage bubbles cannot be edited)', async () => {
+ const { adapter, api, chat } = makeAdapter();
+ await adapter.initialize(chat as any);
+
+ await adapter.editMessage('linq:chat_1', 'msg_out', 'progress…');
+ expect(api.sendText).not.toHaveBeenCalled();
+ });
+});
+
+describe('pickLinqPoolNumber', () => {
+ const pool = ['+15550000001', '+15550000002', '+15550000003'];
+
+ it('is stable per key and stays inside the pool', () => {
+ const picked = pickLinqPoolNumber(pool, 'user_alice');
+ expect(pool).toContain(picked);
+ expect(pickLinqPoolNumber(pool, 'user_alice')).toBe(picked);
+ });
+
+ it('spreads different keys across the pool', () => {
+ const used = new Set(
+ Array.from({ length: 50 }, (_, i) => pickLinqPoolNumber(pool, `user_${i}`)),
+ );
+ expect(used.size).toBe(pool.length);
+ });
+
+ it('refuses an empty pool', () => {
+ expect(() => pickLinqPoolNumber([], 'user_alice')).toThrow(/empty/);
+ });
+});
diff --git a/apps/server/src/services/messenger/platforms/linq/adapter.ts b/apps/server/src/services/messenger/platforms/linq/adapter.ts
new file mode 100644
index 00000000000..464ad982e5c
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/adapter.ts
@@ -0,0 +1,268 @@
+import type {
+ LinqApiClient,
+ LinqInboundMessage,
+ LinqMessagePart,
+ LinqWebhookEvent,
+} from '@lobechat/agent-address-linq';
+import { markdownToPlainText } from '@lobechat/agent-address-linq';
+import type {
+ Adapter,
+ AdapterPostableMessage,
+ Attachment,
+ Author,
+ ChatInstance,
+ EmojiValue,
+ FetchResult,
+ FormattedContent,
+ Logger,
+ RawMessage,
+ Root,
+ ThreadInfo,
+ WebhookOptions,
+} from 'chat';
+import { BaseFormatConverter, Message, parseMarkdown, stringifyMarkdown } from 'chat';
+
+import { linqSenderHandle } from './handle';
+import { decodeLinqThreadId, encodeLinqThreadId } from './threadId';
+
+/** The only Linq event that carries a message from a person. */
+export const LINQ_MESSAGE_RECEIVED_EVENT = 'message.received';
+
+class LinqFormatConverter extends BaseFormatConverter {
+ fromAst(ast: Root): string {
+ return stringifyMarkdown(ast);
+ }
+
+ toAst(text: string): Root {
+ return parseMarkdown(text.trim());
+ }
+}
+
+/** Undo the backslash escapes `stringifyMarkdown` adds for markdown punctuation. */
+const unescapeMarkdown = (text: string): string =>
+ text.replaceAll(/\\([!"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~-])/g, '$1');
+
+/**
+ * The markdown source of a postable. Strings, `raw` and `markdown` are taken as
+ * written: routing them through chat-sdk's AST round-trip would backslash-escape
+ * every `[`, `*` and `_`, and Linq delivers those backslashes verbatim.
+ */
+const postableToMarkdown = (
+ message: AdapterPostableMessage,
+ converter: LinqFormatConverter,
+): string => {
+ if (typeof message === 'string') return message;
+ if ('raw' in message && typeof message.raw === 'string') return message.raw;
+ if ('markdown' in message && typeof message.markdown === 'string') return message.markdown;
+ return unescapeMarkdown(converter.renderPostable(message));
+};
+
+const partsToText = (parts: LinqMessagePart[] | undefined): string =>
+ (parts ?? [])
+ .filter((part): part is Extract<LinqMessagePart, { type: 'text' }> => part.type === 'text')
+ .map((part) => part.value)
+ .join('\n')
+ .trim();
+
+const partsToAttachments = (parts: LinqMessagePart[] | undefined): Attachment[] =>
+ (parts ?? [])
+ .filter(
+ (part): part is Extract<LinqMessagePart, { type: 'media' }> =>
+ part.type === 'media' && !!part.url,
+ )
+ .map(
+ (part) =>
+ ({
+ mimeType: 'application/octet-stream',
+ name: part.url!.split('/').pop()?.split('?')[0] || 'attachment',
+ raw: part,
+ type: 'file',
+ url: part.url!,
+ }) as Attachment,
+ );
+
+export interface LinqChatAdapterConfig {
+ api: LinqApiClient;
+}
+
+/**
+ * Chat SDK adapter over LobeHub's shared Linq number pool.
+ *
+ * Signature verification and replay de-duplication already ran in the
+ * messenger webhook gate, so this adapter only turns a verified
+ * `message.received` delivery into a Chat SDK message. The author id is the
+ * normalized sender handle — that, not the pool number the person texted, is
+ * what `messenger_account_links` routes on.
+ */
+export class LinqChatAdapter implements Adapter<string, LinqInboundMessage> {
+ readonly name = 'linq';
+
+ private readonly api: LinqApiClient;
+ private readonly formatConverter = new LinqFormatConverter();
+
+ private _userName = 'linq-bot';
+ private chat!: ChatInstance;
+ private logger!: Logger;
+
+ constructor(config: LinqChatAdapterConfig) {
+ this.api = config.api;
+ }
+
+ get botUserId(): string {
+ return 'linq:self';
+ }
+
+ get userName(): string {
+ return this._userName;
+ }
+
+ async initialize(chat: ChatInstance): Promise<void> {
+ this.chat = chat;
+ this.logger = chat.getLogger(this.name);
+ this._userName = chat.getUserName();
+ }
+
+ async handleWebhook(request: Request, options?: WebhookOptions): Promise<Response> {
+ let event: LinqWebhookEvent<LinqInboundMessage>;
+ try {
+ event = (await request.json()) as LinqWebhookEvent<LinqInboundMessage>;
+ } catch {
+ return new Response('Invalid JSON', { status: 400 });
+ }
+
+ const data = event.data;
+ if (
+ event.event_type !== LINQ_MESSAGE_RECEIVED_EVENT ||
+ !data?.id ||
+ !data.chat?.id ||
+ data.direction === 'outbound'
+ ) {
+ return Response.json({ ok: true });
+ }
+
+ // Group chats with a pool number are out of scope: the shared bot is a
+ // one-to-one assistant, and a group would leak one member's agent to all.
+ if (data.chat.is_group) {
+ this.logger.info('Ignored Linq group message %s', data.id);
+ return Response.json({ ok: true });
+ }
+
+ if (!linqSenderHandle(data)) {
+ this.logger.warn('Ignored Linq message %s without a sender handle', data.id);
+ return Response.json({ ok: true });
+ }
+
+ const threadId = this.encodeThreadId(data.chat.id);
+ this.chat.processMessage(
+ this,
+ threadId,
+ async () => this.parseInbound(data, threadId),
+ options,
+ );
+ return Response.json({ ok: true });
+ }
+
+ async postMessage(
+ threadId: string,
+ message: AdapterPostableMessage,
+ ): Promise<RawMessage<LinqInboundMessage>> {
+ const chatId = this.decodeThreadId(threadId);
+ // Linq delivers text verbatim — degrade markdown before it leaves.
+ const text = markdownToPlainText(postableToMarkdown(message, this.formatConverter));
+ const sent = await this.api.sendText(chatId, text);
+ return {
+ id: sent.message?.id ?? `local_${Date.now()}`,
+ raw: { chat: { id: chatId }, direction: 'outbound', id: sent.message?.id ?? '' },
+ threadId,
+ };
+ }
+
+ /**
+ * iMessage cannot edit a delivered bubble through Linq. Posting the edit as
+ * a fresh message would spam progress placeholders, so an edit is a no-op
+ * that reports the original id; the final reply always arrives as a post.
+ */
+ async editMessage(
+ threadId: string,
+ messageId: string,
+ _message: AdapterPostableMessage,
+ ): Promise<RawMessage<LinqInboundMessage>> {
+ return {
+ id: messageId,
+ raw: { chat: { id: this.decodeThreadId(threadId) }, id: messageId },
+ threadId,
+ };
+ }
+
+ async deleteMessage(): Promise<void> {}
+
+ async addReaction(_threadId: string, _messageId: string, _emoji: EmojiValue | string) {}
+
+ async removeReaction(_threadId: string, _messageId: string, _emoji: EmojiValue | string) {}
+
+ async fetchMessages(): Promise<FetchResult<LinqInboundMessage>> {
+ return { messages: [], nextCursor: undefined };
+ }
+
+ async fetchThread(threadId: string): Promise<ThreadInfo> {
+ return { channelId: threadId, id: threadId, isDM: true, metadata: {} };
+ }
+
+ async startTyping(threadId: string): Promise<void> {
+ try {
+ await this.api.startTyping(this.decodeThreadId(threadId));
+ } catch (error) {
+ this.logger.warn('startTyping failed for %s: %s', threadId, error);
+ }
+ }
+
+ parseMessage(raw: LinqInboundMessage): Message<LinqInboundMessage> {
+ return this.parseInbound(raw, this.encodeThreadId(raw.chat?.id ?? ''));
+ }
+
+ encodeThreadId(chatId: string): string {
+ return encodeLinqThreadId(chatId);
+ }
+
+ decodeThreadId(threadId: string): string {
+ return decodeLinqThreadId(threadId);
+ }
+
+ channelIdFromThreadId(threadId: string): string {
+ return threadId;
+ }
+
+ isDM(): boolean {
+ return true;
+ }
+
+ renderFormatted(content: FormattedContent): string {
+ return this.formatConverter.fromAst(content);
+ }
+
+ private parseInbound(data: LinqInboundMessage, threadId: string): Message<LinqInboundMessage> {
+ const text = partsToText(data.parts);
+ const userId = linqSenderHandle(data) ?? 'unknown';
+ const author: Author = {
+ fullName: userId,
+ isBot: false,
+ isMe: false,
+ userId,
+ userName: userId,
+ };
+
+ return new Message({
+ attachments: partsToAttachments(data.parts),
+ author,
+ formatted: parseMarkdown(text),
+ id: data.id,
+ metadata: {
+ dateSent: data.sent_at ? new Date(data.sent_at) : new Date(),
+ edited: false,
+ },
+ raw: data,
+ text,
+ threadId,
+ });
+ }
+}
diff --git a/apps/server/src/services/messenger/platforms/linq/binder.test.ts b/apps/server/src/services/messenger/platforms/linq/binder.test.ts
new file mode 100644
index 00000000000..e667613e2e9
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/binder.test.ts
@@ -0,0 +1,187 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { linkLinqSenderByCode, LINQ_REPLY, MessengerLinqBinder } from './binder';
+
+const mocks = vi.hoisted(() => ({
+ consumeLinkCode: vi.fn(),
+ restoreLinkCode: vi.fn(),
+ findByPlatformUser: vi.fn(),
+ sendText: vi.fn(),
+ sendToHandle: vi.fn(),
+ settleLinkCode: vi.fn(),
+ upsertForPlatform: vi.fn(),
+}));
+
+vi.mock('@/config/messenger', () => ({
+ getMessengerLinqConfig: vi.fn(async () => ({
+ apiKey: 'linq_test',
+ numbers: ['+15550000001', '+15550000002'],
+ webhookSecret: 'whsec_test',
+ })),
+}));
+
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.test' } }));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));
+
+vi.mock('@/database/models/messengerAccountLink', () => {
+ class MessengerAccountLinkConflictError extends Error {}
+ class MessengerAccountLinkRelinkRequiredError extends Error {}
+ class MessengerAccountLinkModel {
+ static findByPlatformUser = mocks.findByPlatformUser;
+ constructor(
+ _db: unknown,
+ public userId: string,
+ ) {}
+ upsertForPlatform = (params: unknown) => mocks.upsertForPlatform(this.userId, params);
+ }
+ return {
+ MessengerAccountLinkConflictError,
+ MessengerAccountLinkModel,
+ MessengerAccountLinkRelinkRequiredError,
+ };
+});
+
+vi.mock('../../linkTokenStore', () => ({
+ consumeLinkCode: mocks.consumeLinkCode,
+ restoreLinkCode: mocks.restoreLinkCode,
+ settleLinkCode: mocks.settleLinkCode,
+}));
+
+vi.mock('@lobechat/agent-address-linq', async (importOriginal) => {
+ const actual: Record<string, unknown> = await importOriginal();
+ return {
+ ...actual,
+ LinqApiClient: class {
+ sendText = mocks.sendText;
+ sendToHandle = mocks.sendToHandle;
+ startTyping = vi.fn();
+ },
+ };
+});
+
+const SENDER = '+15550001111';
+
+const unlinked = (text: string) => ({
+ authorUserId: SENDER,
+ chatId: 'chat_1',
+ message: { text } as any,
+});
+
+const pendingCode = {
+ activeAgentId: 'agt_inbox',
+ createdAt: 0,
+ platform: 'linq',
+ pollId: 'poll_1',
+ userId: 'user_alice',
+ workspaceId: null,
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findByPlatformUser.mockResolvedValue(undefined);
+ mocks.upsertForPlatform.mockResolvedValue({ id: 'link_1' });
+});
+
+describe('MessengerLinqBinder.handleUnlinkedMessage', () => {
+ it('binds the sender to whoever issued the code, then confirms in the chat', async () => {
+ mocks.consumeLinkCode.mockResolvedValue(pendingCode);
+
+ await new MessengerLinqBinder().handleUnlinkedMessage(unlinked('Link me LH-7Q2M4XKP'));
+
+ expect(mocks.consumeLinkCode).toHaveBeenCalledWith('LH-7Q2M4XKP', 'linq');
+ expect(mocks.upsertForPlatform).toHaveBeenCalledWith('user_alice', {
+ activeAgentId: 'agt_inbox',
+ platform: 'linq',
+ platformUserId: SENDER,
+ platformUsername: SENDER,
+ tenantId: '',
+ workspaceId: null,
+ });
+ expect(mocks.settleLinkCode).toHaveBeenCalledWith(
+ 'poll_1',
+ expect.objectContaining({ platformUserId: SENDER, status: 'linked' }),
+ );
+ expect(mocks.sendText).toHaveBeenCalledWith('chat_1', LINQ_REPLY.linked());
+ });
+
+ it('points a cold message without a code at the connect page and binds nothing', async () => {
+ await new MessengerLinqBinder().handleUnlinkedMessage(unlinked('hello?'));
+
+ expect(mocks.consumeLinkCode).not.toHaveBeenCalled();
+ expect(mocks.upsertForPlatform).not.toHaveBeenCalled();
+ expect(mocks.sendText).toHaveBeenCalledWith(
+ 'chat_1',
+ expect.stringContaining('https://app.test/settings/messenger/linq'),
+ );
+ });
+
+ it('rejects an expired or already-used code', async () => {
+ mocks.consumeLinkCode.mockResolvedValue(null);
+
+ await new MessengerLinqBinder().handleUnlinkedMessage(unlinked('LH-7Q2M4XKP'));
+
+ expect(mocks.upsertForPlatform).not.toHaveBeenCalled();
+ expect(mocks.sendText).toHaveBeenCalledWith('chat_1', LINQ_REPLY.codeInvalid);
+ });
+
+ it('refuses to move a phone that already belongs to another account', async () => {
+ mocks.consumeLinkCode.mockResolvedValue(pendingCode);
+ mocks.findByPlatformUser.mockResolvedValue({ userId: 'user_bob' });
+
+ await new MessengerLinqBinder().handleUnlinkedMessage(unlinked('LH-7Q2M4XKP'));
+
+ expect(mocks.upsertForPlatform).not.toHaveBeenCalled();
+ expect(mocks.settleLinkCode).toHaveBeenCalledWith('poll_1', {
+ reason: 'already_linked_to_other',
+ status: 'failed',
+ });
+ expect(mocks.sendText).toHaveBeenCalledWith('chat_1', LINQ_REPLY.alreadyLinkedToOther);
+ });
+});
+
+describe('linkLinqSenderByCode', () => {
+ it('puts the consumed code back when the bind fails unexpectedly', async () => {
+ mocks.consumeLinkCode.mockResolvedValue(pendingCode);
+ mocks.restoreLinkCode.mockResolvedValue(undefined);
+ mocks.upsertForPlatform.mockRejectedValue(new Error('connection reset'));
+
+ await expect(linkLinqSenderByCode('LH-7Q2M4XKP', SENDER)).rejects.toThrow('connection reset');
+
+ expect(mocks.restoreLinkCode).toHaveBeenCalledWith('LH-7Q2M4XKP', pendingCode);
+ // Nothing settled — the polling page stays pending, not failed or linked.
+ expect(mocks.settleLinkCode).not.toHaveBeenCalled();
+ });
+
+ it('keeps a committed link when settling the poll status fails afterwards', async () => {
+ mocks.consumeLinkCode.mockResolvedValue(pendingCode);
+ mocks.settleLinkCode.mockRejectedValueOnce(new Error('redis timeout'));
+
+ await expect(linkLinqSenderByCode('LH-7Q2M4XKP', SENDER)).resolves.toEqual({
+ activeAgentId: 'agt_inbox',
+ status: 'linked',
+ });
+ expect(mocks.upsertForPlatform).toHaveBeenCalledTimes(1);
+ // The sender is linked now — resurrecting the code would strand it.
+ expect(mocks.restoreLinkCode).not.toHaveBeenCalled();
+ });
+
+ it('does not restore a code whose outcome was a definitive conflict', async () => {
+ mocks.consumeLinkCode.mockResolvedValue(pendingCode);
+ mocks.findByPlatformUser.mockResolvedValue({ userId: 'user_bob' });
+
+ await expect(linkLinqSenderByCode('LH-7Q2M4XKP', SENDER)).resolves.toEqual({
+ status: 'already_linked_to_other',
+ });
+ expect(mocks.restoreLinkCode).not.toHaveBeenCalled();
+ });
+});
+
+describe('MessengerLinqBinder.sendDmText', () => {
+ it('sends to a handle through the pool when given a phone number', async () => {
+ await new MessengerLinqBinder().sendDmText(SENDER, 'hi');
+ expect(mocks.sendToHandle).toHaveBeenCalledWith({ handle: SENDER, text: 'hi' });
+ expect(mocks.sendText).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/messenger/platforms/linq/binder.ts b/apps/server/src/services/messenger/platforms/linq/binder.ts
new file mode 100644
index 00000000000..d164be8cfec
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/binder.ts
@@ -0,0 +1,193 @@
+import { extractLinqLinkCode } from '@lobechat/agent-address-linq';
+import debug from 'debug';
+
+import { getMessengerLinqConfig, type MessengerLinqConfig } from '@/config/messenger';
+import { getServerDB } from '@/database/core/db-adaptor';
+import {
+ MessengerAccountLinkConflictError,
+ MessengerAccountLinkModel,
+ MessengerAccountLinkRelinkRequiredError,
+} from '@/database/models/messengerAccountLink';
+import { appEnv } from '@/envs/app';
+import type { PlatformClient } from '@/server/services/bot/platforms';
+
+import {
+ consumeLinkCode,
+ type LinkCodePayload,
+ restoreLinkCode,
+ settleLinkCode,
+} from '../../linkTokenStore';
+import type { MessengerPlatformBinder, UnlinkedMessageContext } from '../../types';
+import { LinqMessengerClient, sendLinqTextToHandle } from './client';
+
+const log = debug('lobe-server:messenger:linq:binder');
+
+const settingsUrl = (): string | undefined => {
+ if (!appEnv.APP_URL) return undefined;
+ return new URL('/settings/messenger/linq', appEnv.APP_URL).toString();
+};
+
+/** Replies are deliberately short: they arrive as iMessage / SMS bubbles. */
+export const LINQ_REPLY = {
+ alreadyLinkedToOther:
+ 'This number is already connected to a different LobeHub account. Disconnect it there first, then send your code again.',
+ codeInvalid:
+ 'That link code has expired or was already used. Open LobeHub → Settings → Messenger → iMessage to get a fresh one.',
+ linked: (agentName?: string) =>
+ agentName
+ ? `You're connected to LobeHub. Messages you send here go to ${agentName}.`
+ : "You're connected to LobeHub. Send a message any time.",
+ needLink: (url?: string) =>
+ url
+ ? `Hi! This number isn't connected to LobeHub yet. Open ${url} and tap Connect — it will text us a one-time code from your phone.`
+ : "Hi! This number isn't connected to LobeHub yet. Open LobeHub → Settings → Messenger → iMessage and tap Connect.",
+ unlinkBeforeRelink:
+ 'Your LobeHub account is already connected to another number. Disconnect it in Settings → Messenger first, then send your code again.',
+} as const;
+
+type LinkOutcome =
+ | { activeAgentId: string | null; status: 'linked' }
+ | { status: 'already_linked_to_other' | 'invalid' | 'unlink_before_relink' };
+
+/**
+ * Bind `senderHandle` to whoever issued `code`. The code is consumed before
+ * anything is written so a replayed or forwarded code can never link twice.
+ */
+export const linkLinqSenderByCode = async (
+ code: string,
+ senderHandle: string,
+): Promise<LinkOutcome> => {
+ const payload = await consumeLinkCode(code, 'linq');
+ if (!payload) return { status: 'invalid' };
+
+ try {
+ return await bindConsumedCode(payload, senderHandle);
+ } catch (error) {
+ // The code was taken atomically, but nothing got bound. Put it back so
+ // resending the same code (or the delivery retry) can still complete.
+ await restoreLinkCode(code, payload).catch((restoreError: unknown) => {
+ log('restoreLinkCode failed: %O', restoreError);
+ });
+ throw error;
+ }
+};
+
+const bindConsumedCode = async (
+ payload: LinkCodePayload,
+ senderHandle: string,
+): Promise<LinkOutcome> => {
+ const serverDB = await getServerDB();
+ const owner = await MessengerAccountLinkModel.findByPlatformUser(
+ serverDB,
+ 'linq',
+ senderHandle,
+ '',
+ );
+ if (owner && owner.userId !== payload.userId) {
+ await settleLinkCode(payload.pollId, {
+ reason: 'already_linked_to_other',
+ status: 'failed',
+ });
+ return { status: 'already_linked_to_other' };
+ }
+
+ try {
+ await new MessengerAccountLinkModel(serverDB, payload.userId).upsertForPlatform({
+ activeAgentId: payload.activeAgentId,
+ platform: 'linq',
+ platformUserId: senderHandle,
+ platformUsername: senderHandle,
+ tenantId: '',
+ workspaceId: payload.workspaceId,
+ });
+ } catch (error) {
+ const reason =
+ error instanceof MessengerAccountLinkConflictError
+ ? ('already_linked_to_other' as const)
+ : error instanceof MessengerAccountLinkRelinkRequiredError
+ ? ('unlink_before_relink' as const)
+ : undefined;
+ if (!reason) throw error;
+ await settleLinkCode(payload.pollId, { reason, status: 'failed' });
+ return { status: reason };
+ }
+
+ // The link is committed. A failed poll-status write must not reach the
+ // caller's restore path — that would resurrect a code for a sender who now
+ // routes as linked, so the page would wait on it until expiry.
+ try {
+ await settleLinkCode(payload.pollId, {
+ linkedAt: Date.now(),
+ platformUserId: senderHandle,
+ status: 'linked',
+ });
+ } catch (error) {
+ log('settleLinkCode after link failed: %O', error);
+ }
+ log('linked linq sender for user=%s', payload.userId);
+ return { activeAgentId: payload.activeAgentId, status: 'linked' };
+};
+
+/**
+ * Binder for the shared Linq pool. Unlike Telegram/Slack — where the bot
+ * learns the platform id first and the web page confirms — a Linq link starts
+ * on the web: the signed-in user gets a one-time code and texts it from their
+ * phone. So the unlinked path here is where a link is *completed*, and a cold
+ * message without a code just gets pointed at the connect page.
+ */
+export class MessengerLinqBinder implements MessengerPlatformBinder {
+ private async config(): Promise<MessengerLinqConfig | null> {
+ return getMessengerLinqConfig();
+ }
+
+ async createClient(): Promise<PlatformClient | null> {
+ const config = await this.config();
+ return config ? new LinqMessengerClient(config) : null;
+ }
+
+ async handleUnlinkedMessage(ctx: UnlinkedMessageContext): Promise<void> {
+ const code = extractLinqLinkCode(ctx.message?.text);
+ if (!code) {
+ await this.sendDmText(ctx.chatId, LINQ_REPLY.needLink(settingsUrl()));
+ return;
+ }
+
+ const outcome = await linkLinqSenderByCode(code, ctx.authorUserId);
+ switch (outcome.status) {
+ case 'linked': {
+ await this.sendDmText(ctx.chatId, LINQ_REPLY.linked());
+ return;
+ }
+ case 'invalid': {
+ await this.sendDmText(ctx.chatId, LINQ_REPLY.codeInvalid);
+ return;
+ }
+ case 'already_linked_to_other': {
+ await this.sendDmText(ctx.chatId, LINQ_REPLY.alreadyLinkedToOther);
+ return;
+ }
+ case 'unlink_before_relink': {
+ await this.sendDmText(ctx.chatId, LINQ_REPLY.unlinkBeforeRelink);
+ return;
+ }
+ }
+ }
+
+ async notifyLinkSuccess(params: {
+ activeAgentName?: string;
+ platformUserId: string;
+ }): Promise<void> {
+ await this.sendDmText(params.platformUserId, LINQ_REPLY.linked(params.activeAgentName));
+ }
+
+ /** `chatId` is a Linq chat id on the inbound path, or a handle for proactive sends. */
+ async sendDmText(chatId: string, text: string): Promise<void> {
+ const config = await this.config();
+ if (!config) return;
+ if (chatId.startsWith('+') || chatId.includes('@')) {
+ await sendLinqTextToHandle(config, chatId, text);
+ return;
+ }
+ await new LinqMessengerClient(config).getMessenger(`linq:${chatId}`).createMessage(text);
+ }
+}
diff --git a/apps/server/src/services/messenger/platforms/linq/client.ts b/apps/server/src/services/messenger/platforms/linq/client.ts
new file mode 100644
index 00000000000..cbbc59da5ce
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/client.ts
@@ -0,0 +1,101 @@
+import { LinqApiClient, markdownToPlainText } from '@lobechat/agent-address-linq';
+import debug from 'debug';
+
+import type { MessengerLinqConfig } from '@/config/messenger';
+import {
+ messengerContentText,
+ type PlatformClient,
+ type PlatformMessenger,
+} from '@/server/services/bot/platforms/types';
+
+import { LinqChatAdapter } from './adapter';
+import { pickLinqPoolNumber } from './pool';
+import { decodeLinqThreadId } from './threadId';
+
+const log = debug('lobe-server:messenger:linq:client');
+
+export const LINQ_APPLICATION_ID = 'messenger-linq';
+
+export const createLinqApi = (config: MessengerLinqConfig, fromNumber?: string): LinqApiClient =>
+ new LinqApiClient({ apiKey: config.apiKey, baseUrl: config.apiBaseUrl, fromNumber });
+
+/**
+ * Send to a person by handle rather than by chat id. Reuses the chat the
+ * person already has with the pool (so the reply lands in the same Messages
+ * thread they texted); otherwise opens one from the number this handle is
+ * pinned to in the pool.
+ */
+export const sendLinqTextToHandle = async (
+ config: MessengerLinqConfig,
+ handle: string,
+ text: string,
+): Promise<void> => {
+ const api = createLinqApi(config, pickLinqPoolNumber(config.numbers, handle));
+ await api.sendToHandle({ handle, text: markdownToPlainText(text) });
+};
+
+/** E.164 phone or Apple ID email — anything else is a Linq chat id. */
+const isHandle = (value: string): boolean => value.startsWith('+') || value.includes('@');
+
+/**
+ * `PlatformClient` for the shared Linq pool. Linq is a carrier: there is no
+ * per-agent bot, no slash-command registry, and no editable bubbles — replies
+ * are plain text posted into the person's chat.
+ */
+export class LinqMessengerClient implements PlatformClient {
+ readonly id = 'linq';
+ readonly applicationId = LINQ_APPLICATION_ID;
+
+ constructor(private readonly config: MessengerLinqConfig) {}
+
+ createAdapter(): Record<string, any> {
+ return { linq: new LinqChatAdapter({ api: createLinqApi(this.config) }) };
+ }
+
+ getMessenger(platformThreadId: string): PlatformMessenger {
+ const target = decodeLinqThreadId(platformThreadId);
+ const api = createLinqApi(this.config);
+
+ const send = async (text: string) => {
+ const plain = markdownToPlainText(text).trim();
+ if (!plain) return;
+ if (isHandle(target)) {
+ await sendLinqTextToHandle(this.config, target, plain);
+ return;
+ }
+ await api.sendText(target, plain);
+ };
+
+ return {
+ createMessage: async (content) => send(messengerContentText(content)),
+ // Linq cannot edit a delivered bubble; the definition opts out of edits
+ // so the bridge never relies on this, but a stray edit must not vanish.
+ editMessage: async (_messageId, content) => send(messengerContentText(content)),
+ removeReaction: () => Promise.resolve(),
+ triggerTyping: async () => {
+ if (isHandle(target)) return;
+ try {
+ await api.startTyping(target);
+ } catch (error) {
+ log('triggerTyping failed: %O', error);
+ }
+ },
+ };
+ }
+
+ extractChatId(platformThreadId: string): string {
+ return decodeLinqThreadId(platformThreadId);
+ }
+
+ formatMarkdown(markdown: string): string {
+ return markdownToPlainText(markdown);
+ }
+
+ parseMessageId(compositeId: string): string {
+ return compositeId;
+ }
+
+ async start(): Promise<void> {}
+
+ async stop(): Promise<void> {}
+}
diff --git a/apps/server/src/services/messenger/platforms/linq/definition.ts b/apps/server/src/services/messenger/platforms/linq/definition.ts
new file mode 100644
index 00000000000..2bb5b758316
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/definition.ts
@@ -0,0 +1,18 @@
+import type { MessengerPlatformDefinition } from '../types';
+import { MessengerLinqBinder } from './binder';
+import { linqWebhookGate } from './webhook';
+
+/**
+ * iMessage / SMS through LobeHub's shared Linq number pool. Global like
+ * Telegram (one deployment-level credential bundle, empty tenant), but routed
+ * per sender: the pool numbers are interchangeable and nobody owns one.
+ */
+export const linq: MessengerPlatformDefinition = {
+ connectionMode: 'webhook',
+ createBinder: () => new MessengerLinqBinder(),
+ id: 'linq',
+ name: 'iMessage',
+ supportsMarkdown: false,
+ supportsMessageEdit: false,
+ webhookGate: linqWebhookGate,
+};
diff --git a/apps/server/src/services/messenger/platforms/linq/handle.ts b/apps/server/src/services/messenger/platforms/linq/handle.ts
new file mode 100644
index 00000000000..6c9196d2fbf
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/handle.ts
@@ -0,0 +1,22 @@
+import type { LinqInboundMessage } from '@lobechat/agent-address-linq';
+import { normalizeLinqNumber } from '@lobechat/agent-address-linq';
+
+/**
+ * The stable platform user id for a Linq sender. Phone handles normalize to
+ * E.164 so `+1 (555) 000-2222` and `+15550002222` are one person; iMessage
+ * handles can also be an Apple ID email, which is lower-cased instead.
+ */
+export const normalizeLinqHandle = (raw: string | undefined | null): string | undefined => {
+ const trimmed = raw?.trim();
+ if (!trimmed) return undefined;
+ if (trimmed.includes('@')) return trimmed.toLowerCase();
+ return normalizeLinqNumber(trimmed);
+};
+
+/** The human's handle, across the shapes Linq serializes a sender in. */
+export const linqSenderHandle = (data: LinqInboundMessage): string | undefined => {
+ const raw =
+ data.sender_handle?.handle ??
+ (typeof data.sender === 'string' ? data.sender : data.sender?.handle);
+ return normalizeLinqHandle(raw);
+};
diff --git a/apps/server/src/services/messenger/platforms/linq/index.ts b/apps/server/src/services/messenger/platforms/linq/index.ts
new file mode 100644
index 00000000000..aed851f7ebd
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/index.ts
@@ -0,0 +1,3 @@
+export { MessengerLinqBinder } from './binder';
+export { linq } from './definition';
+export { linqWebhookGate } from './webhook';
diff --git a/apps/server/src/services/messenger/platforms/linq/pool.ts b/apps/server/src/services/messenger/platforms/linq/pool.ts
new file mode 100644
index 00000000000..724b96a0abf
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/pool.ts
@@ -0,0 +1,13 @@
+import { createHash } from 'node:crypto';
+
+/**
+ * Pick the pool number a given key (a LobeHub user id, or a sender handle) is
+ * pointed at. Stable for a fixed pool so the same person keeps seeing the same
+ * number in their Messages thread; any number would work, because inbound is
+ * routed by the sender and never by which pool number received it.
+ */
+export const pickLinqPoolNumber = (numbers: readonly string[], key: string): string => {
+ if (numbers.length === 0) throw new Error('Linq number pool is empty');
+ const digest = createHash('sha256').update(key).digest();
+ return numbers[digest.readUInt32BE(0) % numbers.length];
+};
diff --git a/apps/server/src/services/messenger/platforms/linq/threadId.ts b/apps/server/src/services/messenger/platforms/linq/threadId.ts
new file mode 100644
index 00000000000..5a48a8fe203
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/threadId.ts
@@ -0,0 +1,7 @@
+/** Chat SDK thread ids for Linq are `linq:<chatId>`; the chat id is Linq's own. */
+const PREFIX = 'linq:';
+
+export const encodeLinqThreadId = (chatId: string): string => `${PREFIX}${chatId}`;
+
+export const decodeLinqThreadId = (threadId: string): string =>
+ threadId.startsWith(PREFIX) ? threadId.slice(PREFIX.length) : threadId;
diff --git a/apps/server/src/services/messenger/platforms/linq/webhook.test.ts b/apps/server/src/services/messenger/platforms/linq/webhook.test.ts
new file mode 100644
index 00000000000..8569417cecf
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/webhook.test.ts
@@ -0,0 +1,96 @@
+// @vitest-environment node
+import { signLinqWebhookPayload } from '@lobechat/agent-address-linq';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { linqWebhookGate } from './webhook';
+
+const SECRET = `whsec_${Buffer.from('linq-test-secret').toString('base64')}`;
+
+const config = vi.hoisted(() => ({ value: null as null | Record<string, unknown> }));
+
+vi.mock('@/config/messenger', () => ({
+ getMessengerLinqConfig: vi.fn(async () => config.value),
+}));
+
+const redisStore = vi.hoisted(() => new Map<string, string>());
+
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: vi.fn(() => ({
+ del: vi.fn(async (key: string) => (redisStore.delete(key) ? 1 : 0)),
+ set: vi.fn(async (key: string, value: string, ...args: unknown[]) => {
+ if (args.includes('NX') && redisStore.has(key)) return null;
+ redisStore.set(key, value);
+ return 'OK';
+ }),
+ })),
+}));
+
+const ctx = { invalidateBot: vi.fn() };
+
+const signed = (body: string, id: string, secret = SECRET) => {
+ const timestamp = String(Math.floor(Date.now() / 1000));
+ return new Request('https://app.test/api/agent/messenger/webhooks/linq', {
+ body,
+ headers: {
+ 'webhook-id': id,
+ 'webhook-signature': signLinqWebhookPayload({ body, id, secret, timestamp }),
+ 'webhook-timestamp': timestamp,
+ },
+ method: 'POST',
+ });
+};
+
+const body = JSON.stringify({ data: { id: 'msg_1' }, event_type: 'message.received' });
+
+beforeEach(() => {
+ config.value = { apiKey: 'linq_test', numbers: ['+15550000001'], webhookSecret: SECRET };
+});
+
+describe('linqWebhookGate', () => {
+ it('lets a correctly signed delivery through to the router', async () => {
+ const req = signed(body, `evt_${Math.random()}`);
+ expect(await linqWebhookGate.preprocess(req, body, ctx)).toBeNull();
+ });
+
+ it('rejects a delivery signed with another secret before touching anything', async () => {
+ const other = `whsec_${Buffer.from('not-the-secret').toString('base64')}`;
+ const res = await linqWebhookGate.preprocess(signed(body, 'evt_forged', other), body, ctx);
+ expect(res?.status).toBe(401);
+ });
+
+ it('answers a replayed delivery id as a duplicate', async () => {
+ const id = `evt_${Math.random()}`;
+ expect(await linqWebhookGate.preprocess(signed(body, id), body, ctx)).toBeNull();
+ const res = await linqWebhookGate.preprocess(signed(body, id), body, ctx);
+ expect(res?.status).toBe(409);
+ });
+
+ it('is unavailable until the deployment configures the pool', async () => {
+ config.value = null;
+ const res = await linqWebhookGate.preprocess(signed(body, 'evt_x'), body, ctx);
+ expect(res?.status).toBe(503);
+ });
+
+ it.each([
+ ['the router answered 503', new Response('bot unavailable', { status: 503 })],
+ ['the install was not found', new Response('install not found', { status: 404 })],
+ ['handling threw', undefined],
+ ])('releases the claim so a retry is processed when %s', async (_label, response) => {
+ const id = `evt_${Math.random()}`;
+ expect(await linqWebhookGate.preprocess(signed(body, id), body, ctx)).toBeNull();
+
+ await linqWebhookGate.settle!(signed(body, id), response);
+
+ expect(await linqWebhookGate.preprocess(signed(body, id), body, ctx)).toBeNull();
+ });
+
+ it('keeps the claim after a successful delivery', async () => {
+ const id = `evt_${Math.random()}`;
+ expect(await linqWebhookGate.preprocess(signed(body, id), body, ctx)).toBeNull();
+
+ await linqWebhookGate.settle!(signed(body, id), Response.json({ ok: true }));
+
+ const res = await linqWebhookGate.preprocess(signed(body, id), body, ctx);
+ expect(res?.status).toBe(409);
+ });
+});
diff --git a/apps/server/src/services/messenger/platforms/linq/webhook.ts b/apps/server/src/services/messenger/platforms/linq/webhook.ts
new file mode 100644
index 00000000000..6c745a745c2
--- /dev/null
+++ b/apps/server/src/services/messenger/platforms/linq/webhook.ts
@@ -0,0 +1,91 @@
+import type { LinqWebhookDedupeStore } from '@lobechat/agent-address-linq';
+import {
+ createInMemoryLinqWebhookDedupeStore,
+ LinqWebhookDeduplicator,
+ verifyLinqWebhookRequest,
+} from '@lobechat/agent-address-linq';
+import debug from 'debug';
+
+import { getMessengerLinqConfig } from '@/config/messenger';
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+import type { MessengerPlatformWebhookGate } from '../types';
+
+const log = debug('lobe-server:messenger:linq:webhook-gate');
+
+const memoryStore = createInMemoryLinqWebhookDedupeStore();
+
+/**
+ * Replay claims must be shared across instances — Linq retries a delivery to
+ * whichever instance the load balancer picks. Redis `SET NX EX` gives that;
+ * the bounded in-memory store only covers a Redis-less dev process.
+ */
+const claimKey = (id: string): string => `messenger:linq:webhook-id:${id}`;
+
+const redisDedupeStore: LinqWebhookDedupeStore = {
+ claim: async (id, ttlSeconds) => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return memoryStore.claim(id, ttlSeconds);
+ const result = await redis.set(claimKey(id), '1', 'EX', ttlSeconds, 'NX');
+ return result === 'OK';
+ },
+};
+
+/** Drop a claim so Linq's next retry of this delivery is processed. */
+const releaseClaim = async (id: string): Promise<void> => {
+ const redis = getAgentRuntimeRedisClient();
+ // The in-memory fallback only exists for a Redis-less dev process, where a
+ // lost retry is acceptable; production always has Redis.
+ if (!redis) return;
+ await redis.del(claimKey(id));
+};
+
+const deduplicator = new LinqWebhookDeduplicator(redisDedupeStore);
+
+/**
+ * Linq signs every delivery with the account-level Standard Webhooks secret.
+ * Verify it — and only then claim the delivery id — before any sender
+ * controlled field reaches link lookup or the agent runtime.
+ */
+export const linqWebhookGate: MessengerPlatformWebhookGate = {
+ preprocess: async (req, rawBody) => {
+ const config = await getMessengerLinqConfig();
+ if (!config) {
+ log('webhook: Linq messenger is not configured');
+ return new Response('service not configured', { status: 503 });
+ }
+
+ const verified = await verifyLinqWebhookRequest(req, {
+ deduplicator,
+ rawBody,
+ signingSecret: config.webhookSecret,
+ });
+ if (!verified.ok) {
+ log('webhook: rejected delivery (%d)', verified.response.status);
+ return verified.response;
+ }
+
+ return null;
+ },
+
+ /**
+ * The claim is taken before processing so concurrent retries cannot both
+ * dispatch. If processing then fails (install / bot unavailable, handler
+ * threw), release it — otherwise the retry is answered 409 and the message,
+ * possibly a one-time link code, is lost for good.
+ *
+ * A 2xx keeps the claim. The adapter acknowledges once the message is handed
+ * to chat-sdk's background task, and Linq never redelivers an acknowledged
+ * delivery — so the only retry the claim still sees is a timeout redelivery
+ * racing that background run, which must stay a 409. Background failures are
+ * recovered in-band instead: the router replies with an error the sender can
+ * resend against, and the binder restores a link code whose bind failed.
+ */
+ settle: async (req, response) => {
+ if (response && response.status < 500 && response.status !== 404) return;
+ const id = req.headers.get('webhook-id');
+ if (!id) return;
+ log('webhook: releasing claim %s after failed handling (%s)', id, response?.status ?? 'threw');
+ await releaseClaim(id);
+ },
+};
diff --git a/apps/server/src/services/messenger/platforms/types.ts b/apps/server/src/services/messenger/platforms/types.ts
index a22ba7e2eae..5d13d57e55b 100644
--- a/apps/server/src/services/messenger/platforms/types.ts
+++ b/apps/server/src/services/messenger/platforms/types.ts
@@ -39,6 +39,13 @@ export interface MessengerPlatformWebhookGate {
rawBody: string,
ctx: MessengerWebhookContext,
) => Promise<Response | null>;
+ /**
+ * Called once the router has handled a delivery that passed `preprocess`.
+ * `response` is undefined when handling threw. Gates that claimed the
+ * delivery (replay dedupe) release the claim here on failure so the
+ * platform's retry is processed instead of answered as a duplicate.
+ */
+ settle?: (req: Request, response: Response | undefined) => Promise<void>;
}
/**
@@ -150,6 +157,14 @@ export interface MessengerPlatformDefinition {
* Absent for global-bot platforms (Telegram).
*/
oauth?: MessengerPlatformOAuthAdapter;
+ /**
+ * Reply traits for messenger-only platforms that have no per-agent bot
+ * channel definition in `bot/platforms` (Linq today). Platforms that do have
+ * one (Telegram, Slack, Discord, WeChat) leave these unset — the bridge reads
+ * the bot-channel definition for them.
+ */
+ supportsMarkdown?: boolean;
+ supportsMessageEdit?: boolean;
webhookGate?: MessengerPlatformWebhookGate;
}
diff --git a/apps/server/src/services/messenger/push/index.test.ts b/apps/server/src/services/messenger/push/index.test.ts
index a9ab1df2847..4ea8891d0e2 100644
--- a/apps/server/src/services/messenger/push/index.test.ts
+++ b/apps/server/src/services/messenger/push/index.test.ts
@@ -36,7 +36,7 @@ vi.mock('@/server/services/messenger/wechatPush', () => ({
const serverDB = { kind: 'db' } as unknown as LobeChatDatabase;
-const buildLink = (platform: 'discord' | 'slack' | 'telegram', tenantId = '') => ({
+const buildLink = (platform: 'discord' | 'linq' | 'slack' | 'telegram', tenantId = '') => ({
id: `link-${platform}-${tenantId}`,
platform,
platformUserId: `${platform}-user`,
@@ -71,13 +71,14 @@ afterEach(() => {
describe('messenger proactive push', () => {
it('exposes every currently supported System Bot platform', () => {
- expect(MESSENGER_PUSH_PLATFORMS).toEqual(['telegram', 'slack', 'discord', 'wechat']);
+ expect(MESSENGER_PUSH_PLATFORMS).toEqual(['telegram', 'slack', 'discord', 'wechat', 'linq']);
});
it.each([
['telegram', 'telegram:singleton'],
['discord', 'discord:singleton'],
['slack', 'slack:T_ACME'],
+ ['linq', 'linq:singleton'],
] as const)(
'sends an always-available %s DM with the resolved installation',
async (platform, key) => {
diff --git a/apps/server/src/services/messenger/push/index.ts b/apps/server/src/services/messenger/push/index.ts
index a0805e5d0ef..b5fba11eccd 100644
--- a/apps/server/src/services/messenger/push/index.ts
+++ b/apps/server/src/services/messenger/push/index.ts
@@ -37,6 +37,7 @@ export const MESSENGER_PUSH_PLATFORMS = [
'slack',
'discord',
'wechat',
+ 'linq',
] as const satisfies readonly MessengerPlatform[];
export type MessengerPushPlatform = (typeof MESSENGER_PUSH_PLATFORMS)[number];
diff --git a/locales/en-US/messenger.json b/locales/en-US/messenger.json
index 3f091ecf9a0..9da4566c00e 100644
--- a/locales/en-US/messenger.json
+++ b/locales/en-US/messenger.json
@@ -60,7 +60,26 @@
"messenger.linkModal.notConfigured": "This connection isn't available right now. Please try again later.",
"messenger.linkModal.openCta": "Open in {{platform}}",
"messenger.linkModal.scanHint": "Or scan with your phone to open {{platform}}.",
+ "messenger.linq.accountLabel": "Phone",
+ "messenger.linq.code.expired": "This link code expired. Generate a new one to continue.",
+ "messenger.linq.code.expiresAt": "Valid until {{time}}",
+ "messenger.linq.code.label": "Your one-time link code",
+ "messenger.linq.code.sendTo": "Text it to {{number}}",
+ "messenger.linq.code.tip": "Scan the QR code with your phone camera or tap Open in Messages on your phone, then send the prefilled message. The number is shared — LobeHub recognizes you by the phone you text from. The code works once.",
+ "messenger.linq.code.waiting": "Waiting for your message…",
+ "messenger.linq.connectCta": "Get link code",
+ "messenger.linq.connected": "iMessage connected.",
+ "messenger.linq.error.alreadyLinkedToOther": "This phone number is already connected to another LobeHub account.",
+ "messenger.linq.error.codeUnavailable": "Could not create a link code. Please try again.",
+ "messenger.linq.error.pollFailed": "Could not check the link status. Please generate a new code and try again.",
+ "messenger.linq.error.refreshFailed": "Your phone is connected, but this page could not refresh. Try again.",
+ "messenger.linq.error.unlinkBeforeRelink": "Disconnect the current phone number before connecting another one.",
+ "messenger.linq.openMessages": "Open in Messages",
+ "messenger.linq.refresh": "Refresh",
+ "messenger.linq.retry": "Get a new code",
+ "messenger.linq.setupTitle": "Connect iMessage",
"messenger.list.discord.description": "Chat with your LobeHub agents on Discord by DMing the LobeHub bot from any server.",
+ "messenger.list.linq.description": "Text your LobeHub agents from iMessage or SMS — no app to install, and /agents switches agents.",
"messenger.list.slack.description": "Chat with your LobeHub agents on Slack by DMing or mentioning @LobeHub in any workspace.",
"messenger.list.telegram.description": "Chat with your LobeHub agents on Telegram, and choose which agent replies.",
"messenger.list.wechat.description": "Scan with WeChat to chat privately with your LobeHub agents and switch agents with /agents.",
@@ -130,6 +149,7 @@
"messenger.subtitle": "Connect your account to the official LobeHub bot once. Pick which agent receives messages, switch any time from here or from the bot.",
"messenger.title": "Messenger",
"messenger.unlinkConfirm": "Disconnect your {{platform}} account from LobeHub? Inbound messages will stop until you /start again.",
+ "messenger.unlinkConfirmLinq": "Messages from this phone number will no longer reach your agents. You can reconnect any time with a new link code.",
"messenger.unlinkConfirmWechat": "Disconnect your WeChat account from LobeHub? Inbound messages will stop until you scan the QR code to reconnect.",
"messenger.unlinkCta": "Disconnect",
"messenger.unlinkFailed": "Failed to disconnect.",
diff --git a/locales/zh-CN/messenger.json b/locales/zh-CN/messenger.json
index ebff3964753..410cf9bb1e1 100644
--- a/locales/zh-CN/messenger.json
+++ b/locales/zh-CN/messenger.json
@@ -60,7 +60,26 @@
"messenger.linkModal.notConfigured": "此连接暂不可用,请稍后再试。",
"messenger.linkModal.openCta": "在 {{platform}} 中打开",
"messenger.linkModal.scanHint": "或用手机扫码打开 {{platform}}。",
+ "messenger.linq.accountLabel": "手机号",
+ "messenger.linq.code.expired": "绑定码已过期,请重新生成。",
+ "messenger.linq.code.expiresAt": "{{time}} 前有效",
+ "messenger.linq.code.label": "你的一次性绑定码",
+ "messenger.linq.code.sendTo": "发送到 {{number}}",
+ "messenger.linq.code.tip": "用手机相机扫描二维码,或在手机上点「在信息中打开」,然后发送预填好的消息。号码是共享的,LobeHub 通过你发信的手机号识别你。绑定码仅可使用一次。",
+ "messenger.linq.code.waiting": "正在等待你的消息…",
+ "messenger.linq.connectCta": "获取绑定码",
+ "messenger.linq.connected": "iMessage 已连接。",
+ "messenger.linq.error.alreadyLinkedToOther": "该手机号已连接到另一个 LobeHub 账号。",
+ "messenger.linq.error.codeUnavailable": "无法生成绑定码,请重试。",
+ "messenger.linq.error.pollFailed": "无法查询绑定状态,请重新生成绑定码后重试。",
+ "messenger.linq.error.refreshFailed": "手机号已连接,但页面刷新失败,请重试。",
+ "messenger.linq.error.unlinkBeforeRelink": "请先断开当前手机号,再连接新的号码。",
+ "messenger.linq.openMessages": "在信息中打开",
+ "messenger.linq.refresh": "刷新",
+ "messenger.linq.retry": "重新获取绑定码",
+ "messenger.linq.setupTitle": "连接 iMessage",
"messenger.list.discord.description": "在任意 Discord 服务器中通过私信 LobeHub 机器人与你的 Agent 对话。",
+ "messenger.list.linq.description": "用 iMessage 或短信直接给你的 LobeHub Agent 发消息,无需安装应用,可用 /agents 切换 Agent。",
"messenger.list.slack.description": "在任意 Slack 工作区中通过私信或 @LobeHub 与你的 Agent 对话。",
"messenger.list.telegram.description": "在 Telegram 中与你的 LobeHub Agent 对话,随时切换接收消息的 Agent。",
"messenger.list.wechat.description": "使用微信扫码连接,私聊你的 LobeHub Agent,并可通过 /agents 随时切换。",
@@ -130,6 +149,7 @@
"messenger.subtitle": "将你的账号连接到官方 LobeHub 机器人。选择由哪个 Agent 接收消息,可随时从此处或机器人中切换。",
"messenger.title": "Messenger",
"messenger.unlinkConfirm": "确定要把你的 {{platform}} 账号从 LobeHub 断开吗?在你重新 /start 之前,传入消息将停止。",
+ "messenger.unlinkConfirmLinq": "断开后,来自这个手机号的消息将不再发送给你的 Agent。你可以随时用新的绑定码重新连接。",
"messenger.unlinkConfirmWechat": "确定要把你的 WeChat 账号从 LobeHub 断开吗?在重新扫码连接之前,传入消息将停止。",
"messenger.unlinkCta": "断开",
"messenger.unlinkFailed": "断开失败。",
diff --git a/package.json b/package.json
index 02d00e12e4f..06780868243 100644
--- a/package.json
+++ b/package.json
@@ -227,6 +227,7 @@
"@khmyznikov/pwa-install": "0.3.9",
"@larksuiteoapi/node-sdk": "^1.73.0",
"@lexical/utils": "^0.42.0",
+ "@lobechat/agent-address-linq": "workspace:*",
"@lobechat/agent-gateway-client": "workspace:*",
"@lobechat/agent-mock": "workspace:*",
"@lobechat/agent-runtime": "workspace:*",
diff --git a/packages/agent-address-linq/package.json b/packages/agent-address-linq/package.json
index b9bbd9c488d..29d431ccab5 100644
--- a/packages/agent-address-linq/package.json
+++ b/packages/agent-address-linq/package.json
@@ -1,7 +1,7 @@
{
"name": "@lobechat/agent-address-linq",
"version": "0.1.0",
- "description": "Linq (iMessage / SMS) transport behind an agent's own phone address",
+ "description": "Linq (iMessage / SMS) transport for the shared messenger number pool",
"type": "module",
"exports": {
".": "./src/index.ts"
diff --git a/packages/agent-address-linq/src/deep-link.test.ts b/packages/agent-address-linq/src/deep-link.test.ts
new file mode 100644
index 00000000000..fea27becb48
--- /dev/null
+++ b/packages/agent-address-linq/src/deep-link.test.ts
@@ -0,0 +1,145 @@
+import type * as NodeCrypto from 'node:crypto';
+import { randomInt } from 'node:crypto';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ buildLinqDeepLink,
+ createLinqLinkCode,
+ extractLinqLinkCode,
+ LINQ_LINK_CODE_ALPHABET,
+ LINQ_LINK_CODE_LENGTH,
+ LINQ_LINK_CODE_PATTERN,
+ normalizeLinqNumber,
+} from './deep-link';
+
+vi.mock('node:crypto', async (importOriginal) => {
+ const actual = await importOriginal<typeof NodeCrypto>();
+ return { ...actual, randomInt: vi.fn(actual.randomInt) };
+});
+
+describe('normalizeLinqNumber', () => {
+ it('strips the punctuation people paste around an international number', () => {
+ expect(normalizeLinqNumber('+1 (555) 000-2222')).toBe('+15550002222');
+ expect(normalizeLinqNumber(' +1-555-000-2222 ')).toBe('+15550002222');
+ expect(normalizeLinqNumber('+447700900123')).toBe('+447700900123');
+ });
+
+ it('completes a national-format number from the default country code', () => {
+ expect(normalizeLinqNumber('555 000 2222', { defaultCountryCode: '1' })).toBe('+15550002222');
+ // A leading `0` is a trunk prefix, not part of the subscriber number.
+ expect(normalizeLinqNumber('07700 900123', { defaultCountryCode: '+44' })).toBe(
+ '+447700900123',
+ );
+ });
+
+ it('refuses input it cannot normalize rather than guessing', () => {
+ // A national number with no default country code is ambiguous.
+ expect(normalizeLinqNumber('555 000 2222')).toBeUndefined();
+ expect(normalizeLinqNumber('')).toBeUndefined();
+ expect(normalizeLinqNumber('not a number')).toBeUndefined();
+ // Too short and too long for E.164.
+ expect(normalizeLinqNumber('+1234567')).toBeUndefined();
+ expect(normalizeLinqNumber('+1234567890123456')).toBeUndefined();
+ });
+});
+
+describe('link codes', () => {
+ it('mints a code in the advertised shape', () => {
+ const code = createLinqLinkCode();
+
+ expect(code).toMatch(LINQ_LINK_CODE_PATTERN);
+ expect(code).toHaveLength(3 + LINQ_LINK_CODE_LENGTH);
+ // No glyphs that are mistyped when read off a screen.
+ expect(code.slice(3)).not.toMatch(/[ILO01]/);
+ });
+
+ it('keeps the matcher in step with the alphabet it draws from', () => {
+ // The pattern spells the alphabet as ranges while the minter walks the
+ // string, so pin them together: every mintable glyph matches…
+ for (const glyph of LINQ_LINK_CODE_ALPHABET) {
+ const sample = `LH-${glyph.repeat(LINQ_LINK_CODE_LENGTH)}`;
+ expect(extractLinqLinkCode(sample), `expected ${JSON.stringify(sample)} to match`).toBe(
+ sample,
+ );
+ }
+ // …and none of the excluded ambiguous ones does.
+ for (const glyph of 'ILO01') {
+ const sample = `LH-${glyph.repeat(LINQ_LINK_CODE_LENGTH)}`;
+ expect(extractLinqLinkCode(sample), `expected ${JSON.stringify(sample)} not to match`).toBe(
+ undefined,
+ );
+ }
+ });
+
+ it('draws each symbol uniformly over the alphabet', () => {
+ // A `byte % 31` mapping favours the first 8 symbols; drawing through
+ // `randomInt(alphabet.length)` rejection-samples instead.
+ vi.mocked(randomInt).mockReturnValue((LINQ_LINK_CODE_ALPHABET.length - 1) as never);
+
+ const code = createLinqLinkCode();
+
+ expect(randomInt).toHaveBeenCalledWith(LINQ_LINK_CODE_ALPHABET.length);
+ expect(code).toBe(`LH-${LINQ_LINK_CODE_ALPHABET.at(-1)!.repeat(LINQ_LINK_CODE_LENGTH)}`);
+ vi.mocked(randomInt).mockRestore();
+ });
+
+ it('does not repeat across a burst of mints', () => {
+ const codes = new Set(Array.from({ length: 200 }, () => createLinqLinkCode()));
+ expect(codes.size).toBe(200);
+ });
+
+ it('extracts a code from the message a person actually sends', () => {
+ const code = createLinqLinkCode();
+
+ expect(extractLinqLinkCode(`hey, linking now ${code}`)).toBe(code);
+ // Case-insensitive: a person typing the code by hand still links.
+ expect(extractLinqLinkCode(code.toLowerCase())).toBe(code);
+ expect(extractLinqLinkCode(`Hi! ${code}.`)).toBe(code);
+ });
+
+ it('returns undefined when no code is present', () => {
+ expect(extractLinqLinkCode('just saying hello')).toBeUndefined();
+ expect(extractLinqLinkCode('')).toBeUndefined();
+ expect(extractLinqLinkCode(undefined)).toBeUndefined();
+ // A longer token that merely contains the prefix is not a code.
+ expect(extractLinqLinkCode('X LH-ABCD2345Z')).toBeUndefined();
+ });
+});
+
+describe('buildLinqDeepLink', () => {
+ it('builds both link schemes off the normalized number', () => {
+ const link = buildLinqDeepLink({ number: '+1 (555) 000-2222' });
+
+ expect(link).toEqual({
+ imessage: 'imessage:+15550002222',
+ number: '+15550002222',
+ sms: 'sms:+15550002222',
+ });
+ });
+
+ it('prefills the one-time code so the inbound message is attributable', () => {
+ const code = createLinqLinkCode();
+ const link = buildLinqDeepLink({ code, message: 'Link my agent', number: '+15550002222' });
+
+ expect(link!.body).toBe(`Link my agent ${code}`);
+ // Both platforms' delimiter, and the body survives URL-encoding.
+ expect(link!.sms).toBe(`sms:+15550002222?&body=${encodeURIComponent(`Link my agent ${code}`)}`);
+ expect(link!.imessage).toBe(
+ `imessage:+15550002222?&body=${encodeURIComponent(`Link my agent ${code}`)}`,
+ );
+ });
+
+ it('round-trips: what the deep link prefills is what the inbound extractor finds', () => {
+ const code = createLinqLinkCode();
+ const link = buildLinqDeepLink({ code, number: '+15550002222' });
+
+ expect(link!.body).toBe(code);
+ expect(extractLinqLinkCode(link!.body)).toBe(code);
+ });
+
+ it('omits the body when there is nothing to prefill, and refuses a bad number', () => {
+ expect(buildLinqDeepLink({ number: '+15550002222' })).not.toHaveProperty('body');
+ expect(buildLinqDeepLink({ number: 'who knows' })).toBeUndefined();
+ });
+});
diff --git a/packages/agent-address-linq/src/deep-link.ts b/packages/agent-address-linq/src/deep-link.ts
new file mode 100644
index 00000000000..21fb08d0358
--- /dev/null
+++ b/packages/agent-address-linq/src/deep-link.ts
@@ -0,0 +1,173 @@
+/**
+ * Linq deep links — how a person *starts* the conversation.
+ *
+ * LobeHub never opens a chat with a number that has not messaged it first:
+ * cold outreach on iMessage is the fastest way to get a carrier number flagged
+ * and blocked. The phone link is therefore user-initiated — the product hands
+ * the person a `sms:` / `imessage:` link pointing at one of LobeHub's shared
+ * pool numbers, the person sends it from their own phone, and that first
+ * inbound message is what the signed webhook (and the messenger behind it)
+ * reacts to.
+ *
+ * Pool numbers are interchangeable: inbound routes by the *sender's* handle,
+ * never by which pool number received it. Carrying a one-time **link code** in
+ * the first message is what makes that sender attributable: a cold `"hello"`
+ * from an unknown handle cannot be matched to a LobeHub account, but
+ * `"LH-7Q2M4XKP"` can. This module owns the three primitives that
+ * flow — the code codec, the E.164 normalization the URI needs, and the URI
+ * builders themselves — so every client (web, desktop, mobile, CLI) produces
+ * byte-identical links.
+ *
+ * Deliberately pure: no I/O, no clock, no crypto beyond the CSPRNG used to mint
+ * a code. Issuing, storing and expiring a code is the binding flow's job.
+ */
+
+import { randomInt } from 'node:crypto';
+
+/** Marker that makes a link code recognizable inside an arbitrary message body. */
+export const LINQ_LINK_CODE_PREFIX = 'LH-';
+
+/**
+ * Code alphabet without the glyphs people mistype when reading a code off a
+ * screen: `I`/`L`, `O`/`0`, and `1`. 31 symbols × 8 chars ≈ 47 bits, which is
+ * far beyond what a short-lived, single-use code needs.
+ *
+ * {@link LINQ_LINK_CODE_PATTERN} spells the same set as ranges; `deep-link.test.ts`
+ * pins the two together so they cannot drift.
+ */
+export const LINQ_LINK_CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
+
+/** Number of random symbols in a link code (excluding the prefix). */
+export const LINQ_LINK_CODE_LENGTH = 8;
+
+/**
+ * Matches a link code anywhere in a message, case-insensitively. Boundary
+ * anchored so a longer token that merely contains the prefix is not mistaken
+ * for a code.
+ */
+export const LINQ_LINK_CODE_PATTERN = new RegExp(
+ `\\b${LINQ_LINK_CODE_PREFIX}[A-HJKMNP-Z2-9]{${LINQ_LINK_CODE_LENGTH}}\\b`,
+ 'i',
+);
+
+/**
+ * Mint a link code.
+ *
+ * Uses the CSPRNG, not `Math.random`: the code is what a person's first inbound
+ * message is attributed by, so a guessable code would let one phone number
+ * claim another person's link.
+ */
+export const createLinqLinkCode = (): string => {
+ // `randomInt` rejection-samples, so every symbol is equally likely; a
+ // `byte % 31` mapping would favour the first 8 symbols.
+ let code = '';
+ for (let i = 0; i < LINQ_LINK_CODE_LENGTH; i++) {
+ code += LINQ_LINK_CODE_ALPHABET[randomInt(LINQ_LINK_CODE_ALPHABET.length)];
+ }
+ return `${LINQ_LINK_CODE_PREFIX}${code}`;
+};
+
+/**
+ * Pull a link code out of an inbound message body.
+ *
+ * Returns the normalized (upper-case) code so a person typing the code by hand
+ * in lower case still links, or `undefined` when the message carries none.
+ */
+export const extractLinqLinkCode = (text: string | null | undefined): string | undefined => {
+ if (typeof text !== 'string' || text.length === 0) return undefined;
+ const match = text.match(LINQ_LINK_CODE_PATTERN);
+ return match ? match[0].toUpperCase() : undefined;
+};
+
+export interface LinqNumberOptions {
+ /**
+ * Country calling code (digits only, no `+`) assumed when the input carries
+ * no `+`. Without it a national-format number is ambiguous, so normalization
+ * refuses rather than guessing.
+ */
+ defaultCountryCode?: string;
+}
+
+/**
+ * Normalize a phone number to E.164, or return `undefined` when it cannot be.
+ *
+ * Accepts the formatting people actually paste — `+1 (555) 000-2222`,
+ * `+1-555-000-2222`, `555 000 2222` with a default country code — and rejects
+ * anything whose digit count cannot be E.164.
+ */
+export const normalizeLinqNumber = (
+ raw: string,
+ options: LinqNumberOptions = {},
+): string | undefined => {
+ if (typeof raw !== 'string') return undefined;
+
+ const trimmed = raw.trim();
+ if (!trimmed) return undefined;
+
+ const digits = trimmed.replaceAll(/\D/g, '');
+ if (!digits) return undefined;
+
+ let e164: string;
+ if (trimmed.startsWith('+')) {
+ e164 = digits;
+ } else {
+ const country = options.defaultCountryCode?.replaceAll(/\D/g, '');
+ if (!country) return undefined;
+ // A leading `0` is a national trunk prefix, not part of the subscriber
+ // number; drop it before prepending the country code.
+ e164 = `${country}${digits.replace(/^0+/, '')}`;
+ }
+
+ // E.164 caps a full number at 15 digits; 8 is the shortest real one.
+ if (!/^\d{8,15}$/.test(e164)) return undefined;
+
+ return `+${e164}`;
+};
+
+export interface LinqDeepLinkInput extends LinqNumberOptions {
+ /** One-time code the first message should carry, e.g. from {@link createLinqLinkCode}. */
+ code?: string;
+ /** Optional human-readable line placed before the code. */
+ message?: string;
+ /** Number the person should text — any number from the shared Linq pool. */
+ number: string;
+}
+
+export interface LinqDeepLink {
+ /** Prefilled message body; present only when `message` and/or `code` was given. */
+ body?: string;
+ /** `imessage:` variant — opens Messages directly on Apple devices. */
+ imessage: string;
+ /** The E.164 number both links point at. */
+ number: string;
+ /** `sms:` variant — the cross-platform fallback. */
+ sms: string;
+}
+
+/**
+ * Build the pair of links a person taps to start (or resume) a phone link.
+ *
+ * The `?&body=` delimiter is deliberate rather than sloppy: iOS expects
+ * `...&body=`, Android expects `...?body=`, and the doubled delimiter is the
+ * form both platforms accept. Returns `undefined` for an unusable number so a
+ * caller cannot render a broken link.
+ */
+export const buildLinqDeepLink = (input: LinqDeepLinkInput): LinqDeepLink | undefined => {
+ const number = normalizeLinqNumber(input.number, {
+ defaultCountryCode: input.defaultCountryCode,
+ });
+ if (!number) return undefined;
+
+ const body = [input.message?.trim(), input.code?.trim()].filter(Boolean).join(' ').trim();
+
+ // `encodeURIComponent` keeps the body a single query value — a raw space or
+ // `&` would otherwise truncate the prefilled message.
+ const suffix = body ? `?&body=${encodeURIComponent(body)}` : '';
+
+ return {
+ ...(body ? { body } : {}),
+ imessage: `imessage:${number}${suffix}`,
+ number,
+ sms: `sms:${number}${suffix}`,
+ };
+};
diff --git a/packages/agent-address-linq/src/index.ts b/packages/agent-address-linq/src/index.ts
index 3283982e29a..74ff9e60491 100644
--- a/packages/agent-address-linq/src/index.ts
+++ b/packages/agent-address-linq/src/index.ts
@@ -1,11 +1,12 @@
/**
- * Linq transport — the provider behind an agent's own `phone` address.
+ * Linq transport — LobeHub's shared iMessage / SMS number pool.
*
* Linq is a carrier (iMessage / SMS), not a social platform: this package owns
- * the REST client, Standard Webhooks verification + replay dedupe, and the
- * markdown → plain-text degradation Linq requires. There is no chat-SDK
- * adapter here, and no per-agent bot registration — the number is shared
- * infrastructure, the agent merely owns an address on it.
+ * the REST client, Standard Webhooks verification + replay dedupe, the
+ * markdown → plain-text degradation Linq requires, and the link-code / deep
+ * link primitives a person uses to start a conversation. The numbers are shared
+ * infrastructure — no agent or user owns one; the messenger routes each
+ * inbound message by its sender.
*/
export {
assertSendableParts,
@@ -13,6 +14,17 @@ export {
LINQ_URL_MEDIA_MAX_BYTES,
LinqApiClient,
} from './api';
+export type { LinqDeepLink, LinqDeepLinkInput, LinqNumberOptions } from './deep-link';
+export {
+ buildLinqDeepLink,
+ createLinqLinkCode,
+ extractLinqLinkCode,
+ LINQ_LINK_CODE_ALPHABET,
+ LINQ_LINK_CODE_LENGTH,
+ LINQ_LINK_CODE_PATTERN,
+ LINQ_LINK_CODE_PREFIX,
+ normalizeLinqNumber,
+} from './deep-link';
export { markdownToPlainText } from './format-converter';
export type {
LinqApiConfig,
diff --git a/packages/app-config/src/messenger.ts b/packages/app-config/src/messenger.ts
index 08ff303c8c9..8ff3a1bbe41 100644
--- a/packages/app-config/src/messenger.ts
+++ b/packages/app-config/src/messenger.ts
@@ -50,7 +50,7 @@ export const getMessengerConfig = () => {
export const messengerEnv = getMessengerConfig();
-export type MessengerPlatform = 'telegram' | 'slack' | 'discord' | 'wechat';
+export type MessengerPlatform = 'telegram' | 'slack' | 'discord' | 'wechat' | 'linq';
export interface MessengerTelegramConfig {
botToken: string;
@@ -86,6 +86,32 @@ export interface MessengerWechatConfig {
enabled: true;
}
+/**
+ * Linq (iMessage / SMS) — a pool of LobeHub-owned numbers shared by every
+ * user. No number belongs to a user or an agent: inbound routes by the
+ * sender's handle, and a person links their phone by texting a one-time code
+ * to any pool number.
+ */
+export interface MessengerLinqConfig {
+ /** REST base override; defaults to the Linq package's `https://api.linqapp.com/v3`. */
+ apiBaseUrl?: string;
+ apiKey: string;
+ /** Shared pool numbers in E.164. Never empty. */
+ numbers: string[];
+ /** Standard Webhooks signing secret (`whsec_…`) of the account-level webhook. */
+ webhookSecret: string;
+}
+
+/** Accept the pool as a JSON array or a comma / whitespace separated string. */
+export const parseLinqNumberPool = (raw: unknown): string[] => {
+ const values = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(/[\s,]+/) : [];
+ const numbers = values
+ .filter((value): value is string => typeof value === 'string')
+ .map((value) => value.trim())
+ .filter((value) => /^\+\d{8,15}$/.test(value));
+ return [...new Set(numbers)];
+};
+
// ---------------------------------------------------------------------------
// In-process cache.
//
@@ -201,6 +227,28 @@ export const getMessengerWechatConfig = async (): Promise<MessengerWechatConfig
return fetchAndCache<MessengerWechatConfig>('wechat', () => ({ enabled: true }));
};
+export const getMessengerLinqConfig = async (): Promise<MessengerLinqConfig | null> => {
+ // Link codes and webhook replay claims live in Redis; without it a person
+ // could never complete a link, so the platform is not advertised.
+ if (!redisEnv.REDIS_URL || process.env.DISABLE_REDIS) return null;
+
+ return fetchAndCache<MessengerLinqConfig>('linq', (row) => {
+ const c = row.credentials as Partial<
+ Record<'apiBaseUrl' | 'apiKey' | 'webhookSecret', string>
+ > & {
+ numbers?: unknown;
+ };
+ const numbers = parseLinqNumberPool(c.numbers);
+ if (!c.apiKey || !c.webhookSecret || numbers.length === 0) return null;
+ return {
+ apiBaseUrl: c.apiBaseUrl || undefined,
+ apiKey: c.apiKey,
+ numbers,
+ webhookSecret: c.webhookSecret,
+ };
+ });
+};
+
export const isMessengerPlatformEnabled = async (platform: MessengerPlatform): Promise<boolean> => {
switch (platform) {
case 'telegram': {
@@ -215,6 +263,9 @@ export const isMessengerPlatformEnabled = async (platform: MessengerPlatform): P
case 'wechat': {
return !!(await getMessengerWechatConfig());
}
+ case 'linq': {
+ return !!(await getMessengerLinqConfig());
+ }
default: {
return false;
}
@@ -222,7 +273,7 @@ export const isMessengerPlatformEnabled = async (platform: MessengerPlatform): P
};
export const getEnabledMessengerPlatforms = async (): Promise<MessengerPlatform[]> => {
- const platforms = ['telegram', 'slack', 'discord', 'wechat'] as const;
+ const platforms = ['telegram', 'slack', 'discord', 'wechat', 'linq'] as const;
const checks = await Promise.all(
platforms.map(async (p) => ((await isMessengerPlatformEnabled(p)) ? p : null)),
);
diff --git a/packages/builtin-tool-message/src/manifest.test.ts b/packages/builtin-tool-message/src/manifest.test.ts
index a92526dca78..b5dd3a6f8cd 100644
--- a/packages/builtin-tool-message/src/manifest.test.ts
+++ b/packages/builtin-tool-message/src/manifest.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { MessageManifest } from './manifest';
-import { MessageApiName } from './types';
+import { MessageApiName, MessengerPushPlatform } from './types';
const findApi = (name: string) => MessageManifest.api.find((api) => api.name === name);
@@ -29,4 +29,13 @@ describe('MessageManifest', () => {
expect(findApi(name)?.ordered, name).toBeUndefined();
}
});
+
+ // The schema is what the model is held to: a platform the server can push
+ // to but the enum omits is rejected before the call ever reaches it.
+ it('advertises every proactive push platform in the sendMessengerPush schema', () => {
+ const platform = (findApi(MessageApiName.sendMessengerPush)?.parameters as any).properties
+ .platform;
+ expect([...platform.enum].sort()).toEqual(Object.values(MessengerPushPlatform).sort());
+ expect(platform.enum).toContain('linq');
+ });
});
diff --git a/packages/builtin-tool-message/src/manifest.ts b/packages/builtin-tool-message/src/manifest.ts
index 3de0bd51f88..185ee7c050f 100644
--- a/packages/builtin-tool-message/src/manifest.ts
+++ b/packages/builtin-tool-message/src/manifest.ts
@@ -1087,7 +1087,7 @@ export const MessageManifest: BuiltinToolManifest = {
},
{
description:
- 'Proactively push a message to the CURRENT USER\'s own DM with the LobeHub System Bot — THE api for "send me a message on <platform>", "DM me", "notify me when done". Unlike `sendDirectMessage` it needs no bot discovery, channel id, or platform user id: the server resolves the user\'s own account link. Availability comes from that account link, NOT from `listBots` / `listMessengers` — a platform missing there can still be pushable, so never refuse based on those lists. Call `listMessengerLinks` when unsure which platforms are linked; when the user named one, just push and let an `unlinked` status tell you. Telegram / Discord deliver immediately. Slack with several linked workspaces returns `needs_workspace_selection` — ask the user to pick, then retry with that `tenantId`. WeChat can only deliver inside the send window opened by the user\'s last inbound message; outside it the push is `queued` and you must tell the user to message the LobeHub WeChat bot first so the queued push gets delivered.',
+ 'Proactively push a message to the CURRENT USER\'s own DM with the LobeHub System Bot — THE api for "send me a message on <platform>", "DM me", "notify me when done". Unlike `sendDirectMessage` it needs no bot discovery, channel id, or platform user id: the server resolves the user\'s own account link. Availability comes from that account link, NOT from `listBots` / `listMessengers` — a platform missing there can still be pushable, so never refuse based on those lists. Call `listMessengerLinks` when unsure which platforms are linked; when the user named one, just push and let an `unlinked` status tell you. Telegram / Discord / iMessage-SMS (`linq`) deliver immediately. Slack with several linked workspaces returns `needs_workspace_selection` — ask the user to pick, then retry with that `tenantId`. WeChat can only deliver inside the send window opened by the user\'s last inbound message; outside it the push is `queued` and you must tell the user to message the LobeHub WeChat bot first so the queued push gets delivered.',
name: MessageApiName.sendMessengerPush,
ordered: true,
parameters: {
@@ -1101,8 +1101,9 @@ export const MessageManifest: BuiltinToolManifest = {
type: 'string',
},
platform: {
- description: 'Platform to push to — must be one the user has linked.',
- enum: ['telegram', 'slack', 'discord', 'wechat'],
+ description:
+ "Platform to push to — must be one the user has linked. `linq` is iMessage / SMS to the user's linked phone number.",
+ enum: ['telegram', 'slack', 'discord', 'wechat', 'linq'],
type: 'string',
},
tenantId: {
diff --git a/packages/builtin-tool-message/src/systemRole.ts b/packages/builtin-tool-message/src/systemRole.ts
index 5126963fa96..cd24e2aa314 100644
--- a/packages/builtin-tool-message/src/systemRole.ts
+++ b/packages/builtin-tool-message/src/systemRole.ts
@@ -71,11 +71,11 @@ When in doubt, ask. Defaulting to the destructive option (\`uninstallMessenger\`
</system_bot_management>
<proactive_push>
-**sendMessengerPush** — proactively push a message to the **current user's own DM** with the LobeHub System Bot. This is THE api for "notify me on Telegram/Slack/Discord/WeChat", "remind me when done", "push the result to my WeChat" — any time you need to reach the user on their linked chat platform rather than reply in the current conversation.
+**sendMessengerPush** — proactively push a message to the **current user's own DM** with the LobeHub System Bot. This is THE api for "notify me on Telegram/Slack/Discord/WeChat/iMessage", "remind me when done", "push the result to my WeChat" — any time you need to reach the user on their linked chat platform rather than reply in the current conversation.
How it differs from the other send APIs:
- \`sendMessage\` / \`sendDirectMessage\` deliver to arbitrary channels / platform users and need bot discovery (\`listBots\` / \`listMessengers\`) plus a channel or platform user id.
-- \`sendMessengerPush\` targets **the user themselves** — no discovery, no ids. The server resolves the user's own account link. Just pass \`platform\` + \`content\`.
+- \`sendMessengerPush\` targets **the user themselves** — no discovery, no ids. The server resolves the user's own account link. Just pass \`platform\` + \`content\`. iMessage / SMS (text me, message my phone) is \`platform: 'linq'\`.
**Do not gate this API on \`listMessengers\`.** Deliverability comes from the user's account link, which is a different record from a System Bot installation — a platform can be perfectly pushable while absent from \`listMessengers\` (and a per-agent bot sitting at \`status: disconnected\` says nothing about it either). When you want to check first, call \`listMessengerLinks\`. When the user already named the platform, skip the check and just push: an unlinked platform comes back as \`unlinked\`, which is cheaper and more reliable than inferring it from a list.
diff --git a/packages/builtin-tool-message/src/types.ts b/packages/builtin-tool-message/src/types.ts
index d72fb203810..79196bed457 100644
--- a/packages/builtin-tool-message/src/types.ts
+++ b/packages/builtin-tool-message/src/types.ts
@@ -815,6 +815,7 @@ export const MESSENGER_PUSH_CONTENT_MAX_LENGTH = 2000;
export const MessengerPushPlatform = {
discord: 'discord',
+ linq: 'linq',
slack: 'slack',
telegram: 'telegram',
wechat: 'wechat',
diff --git a/packages/const/src/bot.ts b/packages/const/src/bot.ts
index 4e50ae98593..c4340b9c284 100644
--- a/packages/const/src/bot.ts
+++ b/packages/const/src/bot.ts
@@ -36,6 +36,7 @@ export const MIN_BOT_HISTORY_LIMIT = 1;
* - wechat: 2MB image — empirical: iLink silently drops larger images
* (every API call returns 200 yet the message never renders); 20MB file
* as a best-effort cap, the iLink protocol documents no explicit number.
+ * - linq: 10MB — Linq's documented ceiling for media it fetches by URL.
*
* `textMaxChars` is the single-message character cap used to batch the
* download-link fallbacks: Discord rejects a message over 2000 chars,
@@ -57,10 +58,11 @@ export interface MessengerAttachmentBudget {
const MB = 1024 * 1024;
export const MESSENGER_ATTACHMENT_BUDGETS: Record<
- 'discord' | 'slack' | 'telegram' | 'wechat',
+ 'discord' | 'slack' | 'telegram' | 'wechat' | 'linq',
MessengerAttachmentBudget
> = {
discord: { fileMaxBytes: 10 * MB, imageMaxBytes: 10 * MB, textMaxChars: 2000 },
+ linq: { fileMaxBytes: 10 * MB, imageMaxBytes: 10 * MB, textMaxChars: 2000 },
slack: { fileMaxBytes: 50 * MB, imageMaxBytes: 50 * MB, textMaxChars: 3000 },
telegram: { fileMaxBytes: 20 * MB, imageMaxBytes: 5 * MB, textMaxChars: 4096 },
wechat: { fileMaxBytes: 20 * MB, imageMaxBytes: 2 * MB, textMaxChars: 2000 },
diff --git a/packages/locales/src/default/messenger.ts b/packages/locales/src/default/messenger.ts
index 88cce69f853..254720f326e 100644
--- a/packages/locales/src/default/messenger.ts
+++ b/packages/locales/src/default/messenger.ts
@@ -278,4 +278,31 @@ export default {
'Your account is now connected to {{platform}}. Open {{platform}} and send your first message.',
'verify.success.openBot': 'Open in {{platform}}',
'verify.success.title': 'Linked successfully!',
+ 'messenger.linq.accountLabel': 'Phone',
+ 'messenger.linq.code.expired': 'This link code expired. Generate a new one to continue.',
+ 'messenger.linq.code.label': 'Your one-time link code',
+ 'messenger.linq.code.sendTo': 'Text it to {{number}}',
+ 'messenger.linq.code.tip':
+ 'Scan the QR code with your phone camera or tap Open in Messages on your phone, then send the prefilled message. The number is shared — LobeHub recognizes you by the phone you text from. The code works once.',
+ 'messenger.linq.code.waiting': 'Waiting for your message…',
+ 'messenger.linq.connectCta': 'Get link code',
+ 'messenger.linq.connected': 'iMessage connected.',
+ 'messenger.linq.error.alreadyLinkedToOther':
+ 'This phone number is already connected to another LobeHub account.',
+ 'messenger.linq.error.codeUnavailable': 'Could not create a link code. Please try again.',
+ 'messenger.linq.error.pollFailed':
+ 'Could not check the link status. Please generate a new code and try again.',
+ 'messenger.linq.error.unlinkBeforeRelink':
+ 'Disconnect the current phone number before connecting another one.',
+ 'messenger.linq.openMessages': 'Open in Messages',
+ 'messenger.linq.retry': 'Get a new code',
+ 'messenger.linq.setupTitle': 'Connect iMessage',
+ 'messenger.list.linq.description':
+ 'Text your LobeHub agents from iMessage or SMS — no app to install, and /agents switches agents.',
+ 'messenger.unlinkConfirmLinq':
+ 'Messages from this phone number will no longer reach your agents. You can reconnect any time with a new link code.',
+ 'messenger.linq.code.expiresAt': 'Valid until {{time}}',
+ 'messenger.linq.error.refreshFailed':
+ 'Your phone is connected, but this page could not refresh. Try again.',
+ 'messenger.linq.refresh': 'Refresh',
};
diff --git a/src/features/Messenger/IntegrationDetail/Linq.test.tsx b/src/features/Messenger/IntegrationDetail/Linq.test.tsx
new file mode 100644
index 00000000000..2faa5075e1c
--- /dev/null
+++ b/src/features/Messenger/IntegrationDetail/Linq.test.tsx
@@ -0,0 +1,83 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LinqLinkSetup } from './Linq';
+
+const messengerServiceMocks = vi.hoisted(() => ({
+ createLinqLink: vi.fn(),
+ pollLinqLink: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ QRCode: ({ value }: { value: string }) => <span data-value={value} role="img" />,
+}));
+
+vi.mock('antd-style', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ createStaticStyles: () => ({ code: 'code', qrSlot: 'qrSlot', setup: 'setup', tips: 'tips' }),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, params?: Record<string, string>) =>
+ params?.time ? `${key}:${params.time}` : key,
+ }),
+}));
+
+vi.mock('@/services/messenger', () => ({ messengerService: messengerServiceMocks }));
+vi.mock('../i18n', () => ({ getMessengerErrorMessage: () => 'refresh failed' }));
+vi.mock('./MessengerPush', () => ({ MessengerPushSection: () => null }));
+vi.mock('./shared', () => ({
+ DetailLayout: () => null,
+ IntegrationDetailSkeleton: () => null,
+ UserAgentConnection: () => null,
+ useLinkActions: () => ({}),
+ useMessengerData: () => ({ links: [] }),
+}));
+
+describe('LinqLinkSetup', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ messengerServiceMocks.createLinqLink.mockResolvedValue({
+ code: 'LH-QA8VN5BP',
+ deepLink: {
+ imessage: 'imessage:+15550100002?&body=LH-QA8VN5BP',
+ number: '+15550100002',
+ sms: 'sms:+15550100002?&body=LH-QA8VN5BP',
+ },
+ expiresAt: Date.now() + 10 * 60 * 1000,
+ pollId: 'poll_1',
+ });
+ });
+
+ it('points the primary action at the cross-platform sms: link and shows the server expiry', async () => {
+ messengerServiceMocks.pollLinqLink.mockResolvedValue({ status: 'pending' });
+ render(<LinqLinkSetup onLinked={vi.fn()} />);
+ fireEvent.click(screen.getByRole('button', { name: 'messenger.linq.connectCta' }));
+
+ const open = await screen.findByRole('link', { name: /messenger.linq.openMessages/ });
+ expect(open).toHaveAttribute('href', 'sms:+15550100002?&body=LH-QA8VN5BP');
+ expect(screen.getByText(/^messenger\.linq\.code\.expiresAt:/)).toBeInTheDocument();
+ });
+
+ it('retries only the refresh, never a new code, when refreshing after a link fails', async () => {
+ messengerServiceMocks.pollLinqLink.mockResolvedValue({ status: 'linked' });
+ const onLinked = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('swr down'))
+ .mockResolvedValue(undefined);
+ render(<LinqLinkSetup onLinked={onLinked} />);
+ fireEvent.click(screen.getByRole('button', { name: 'messenger.linq.connectCta' }));
+ await screen.findByRole('link', { name: /messenger.linq.openMessages/ });
+ await vi.advanceTimersByTimeAsync(2100);
+
+ const refresh = await screen.findByRole('button', { name: /messenger.linq.refresh/ });
+ expect(screen.queryByRole('button', { name: /messenger.linq.retry/ })).toBeNull();
+
+ fireEvent.click(refresh);
+ await waitFor(() => expect(onLinked).toHaveBeenCalledTimes(2));
+ expect(messengerServiceMocks.createLinqLink).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/Messenger/IntegrationDetail/Linq.tsx b/src/features/Messenger/IntegrationDetail/Linq.tsx
new file mode 100644
index 00000000000..67b121fe69c
--- /dev/null
+++ b/src/features/Messenger/IntegrationDetail/Linq.tsx
@@ -0,0 +1,319 @@
+'use client';
+
+import { Block, Flexbox, Icon } from '@lobehub/ui';
+import { Alert, Button, QRCode, Spin, Text, toast } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { InfoIcon, MessageCircleIcon, RefreshCwIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { usePermission } from '@/hooks/usePermission';
+import { messengerService } from '@/services/messenger';
+
+import { getMessengerErrorMessage } from '../i18n';
+import { MessengerPushSection } from './MessengerPush';
+import {
+ DetailLayout,
+ IntegrationDetailSkeleton,
+ useLinkActions,
+ useMessengerData,
+ UserAgentConnection,
+} from './shared';
+
+const POLL_INTERVAL_MS = 2000;
+const QR_SIZE = 200;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ code: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 20px;
+ font-weight: 600;
+ letter-spacing: 0.08em;
+ `,
+ qrSlot: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: ${QR_SIZE + 20}px;
+ height: ${QR_SIZE + 20}px;
+ padding: 9px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ setup: css`
+ align-items: center;
+
+ padding-block: 32px;
+ padding-inline: 20px;
+ border: 1px solid ${cssVar.colorBorder};
+ border-radius: ${cssVar.borderRadius};
+ `,
+ tips: css`
+ max-width: 480px;
+ font-size: ${cssVar.fontSize};
+ text-align: center;
+ `,
+}));
+
+interface LinqLinkSession {
+ code: string;
+ deepLink: { body?: string; imessage: string; number: string; sms: string };
+ expiresAt: number;
+ pollId: string;
+}
+
+type SetupState =
+ | { stage: 'idle' }
+ | { stage: 'loading' }
+ | { message: string; stage: 'error' }
+ // The link exists server-side; only the local refresh is pending / failed.
+ // Never offer a new code from here — `createLinqLink` would answer CONFLICT.
+ | { stage: 'linked' }
+ | { message: string; stage: 'refreshError' }
+ | { session: LinqLinkSession; stage: 'waiting' };
+
+interface LinqLinkSetupProps {
+ disabled?: boolean;
+ onLinked: () => Promise<void>;
+}
+
+/**
+ * Web-initiated link: show a one-time code and an `sms:` deep link prefilled
+ * with it (as a QR code for desktop, as a button on the phone). The person
+ * sends it from their own phone to the shared pool; the inbound sender becomes
+ * the linked identity, and this view polls until the server sees it.
+ */
+const LinqLinkSetup = memo<LinqLinkSetupProps>(({ disabled, onLinked }) => {
+ const { t } = useTranslation('messenger');
+ const [state, setState] = useState<SetupState>({ stage: 'idle' });
+ const aliveRef = useRef(true);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const stopPolling = useCallback(() => {
+ if (timerRef.current) clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }, []);
+
+ useEffect(() => {
+ aliveRef.current = true;
+ return () => {
+ aliveRef.current = false;
+ stopPolling();
+ };
+ }, [stopPolling]);
+
+ const finishLinked = useCallback(async () => {
+ setState({ stage: 'linked' });
+ try {
+ await onLinked();
+ } catch (error) {
+ if (!aliveRef.current) return;
+ setState({
+ message: getMessengerErrorMessage(error, t, 'messenger.linq.error.refreshFailed'),
+ stage: 'refreshError',
+ });
+ }
+ }, [onLinked, t]);
+
+ const start = useCallback(async () => {
+ if (disabled) return;
+ stopPolling();
+ setState({ stage: 'loading' });
+
+ try {
+ const session = await messengerService.createLinqLink();
+ if (!aliveRef.current) return;
+ setState({ session, stage: 'waiting' });
+
+ const poll = async (): Promise<void> => {
+ if (!aliveRef.current) return;
+ try {
+ const result = await messengerService.pollLinqLink(session.pollId);
+ if (!aliveRef.current) return;
+
+ if (result.status === 'linked') {
+ stopPolling();
+ await finishLinked();
+ return;
+ }
+ if (result.status === 'expired') {
+ stopPolling();
+ setState({ message: t('messenger.linq.code.expired'), stage: 'error' });
+ return;
+ }
+ if (result.status === 'failed') {
+ stopPolling();
+ setState({
+ message:
+ result.reason === 'already_linked_to_other'
+ ? t('messenger.linq.error.alreadyLinkedToOther')
+ : t('messenger.linq.error.unlinkBeforeRelink'),
+ stage: 'error',
+ });
+ return;
+ }
+ timerRef.current = setTimeout(poll, POLL_INTERVAL_MS);
+ } catch (error) {
+ stopPolling();
+ setState({
+ message: getMessengerErrorMessage(error, t, 'messenger.linq.error.pollFailed'),
+ stage: 'error',
+ });
+ }
+ };
+
+ timerRef.current = setTimeout(poll, POLL_INTERVAL_MS);
+ } catch (error) {
+ setState({
+ message: getMessengerErrorMessage(error, t, 'messenger.linq.error.codeUnavailable'),
+ stage: 'error',
+ });
+ }
+ }, [disabled, finishLinked, stopPolling, t]);
+
+ return (
+ <Block className={styles.setup}>
+ <Flexbox align="center" gap={12}>
+ {state.stage === 'idle' && (
+ <Button
+ disabled={disabled}
+ icon={<Icon icon={MessageCircleIcon} />}
+ type="primary"
+ onClick={start}
+ >
+ {t('messenger.linq.connectCta')}
+ </Button>
+ )}
+ {(state.stage === 'loading' || state.stage === 'linked') && <Spin size="large" />}
+ {state.stage === 'waiting' && (
+ <>
+ <div className={styles.qrSlot}>
+ <QRCode
+ aria-label={t('messenger.linq.setupTitle')}
+ bgColor="#fff"
+ bordered={false}
+ color="#000"
+ size={QR_SIZE}
+ value={state.session.deepLink.sms}
+ />
+ </div>
+ <Text type="secondary">{t('messenger.linq.code.label')}</Text>
+ <Text className={styles.code} data-testid="linq-link-code">
+ {state.session.code}
+ </Text>
+ <Text type="secondary">
+ {t('messenger.linq.code.sendTo', { number: state.session.deepLink.number })}
+ </Text>
+ <Button
+ href={state.session.deepLink.sms}
+ icon={<Icon icon={MessageCircleIcon} />}
+ type="primary"
+ >
+ {t('messenger.linq.openMessages')}
+ </Button>
+ <Text type="secondary">
+ {t('messenger.linq.code.expiresAt', {
+ time: new Date(state.session.expiresAt).toLocaleTimeString([], {
+ hour: '2-digit',
+ minute: '2-digit',
+ }),
+ })}
+ </Text>
+ <Text type="secondary">{t('messenger.linq.code.waiting')}</Text>
+ </>
+ )}
+ {state.stage === 'error' && (
+ <Flexbox align="center" gap={12} width="100%">
+ <Alert showIcon message={state.message} type="warning" />
+ <Button
+ disabled={disabled}
+ icon={<Icon icon={RefreshCwIcon} />}
+ type="primary"
+ onClick={start}
+ >
+ {t('messenger.linq.retry')}
+ </Button>
+ </Flexbox>
+ )}
+
+ {state.stage === 'refreshError' && (
+ <Flexbox align="center" gap={12} width="100%">
+ <Alert showIcon message={state.message} type="warning" />
+ <Button icon={<Icon icon={RefreshCwIcon} />} type="primary" onClick={finishLinked}>
+ {t('messenger.linq.refresh')}
+ </Button>
+ </Flexbox>
+ )}
+
+ <Text className={styles.tips} type="secondary">
+ <Icon icon={InfoIcon} style={{ marginInlineEnd: 4 }} />
+ {t('messenger.linq.code.tip')}
+ </Text>
+ </Flexbox>
+ </Block>
+ );
+});
+LinqLinkSetup.displayName = 'MessengerLinqLinkSetup';
+
+export { LinqLinkSetup };
+
+interface LinqDetailProps {
+ name: string;
+ onBack: () => void;
+}
+
+const LinqDetail = memo<LinqDetailProps>(({ name, onBack }) => {
+ const { t } = useTranslation('messenger');
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const data = useMessengerData('linq');
+ const { handleSetActive, handleUnlink } = useLinkActions({
+ installationsMutate: data.installationsMutate,
+ linksMutate: data.linksMutate,
+ name,
+ platform: 'linq',
+ });
+
+ if (data.error && data.isInitialLoading)
+ return <AsyncError error={data.error} variant="block" onRetry={data.mutate} />;
+ if (data.isInitialLoading) return <IntegrationDetailSkeleton withNestedContent />;
+
+ const link = data.links[0];
+
+ const handleLinked = async () => {
+ await data.linksMutate();
+ toast.success(t('messenger.linq.connected'));
+ };
+
+ return (
+ <DetailLayout
+ hasConnections
+ extraSections={link ? <MessengerPushSection name={name} platform="linq" /> : undefined}
+ headerAction={null}
+ name={name}
+ platform="linq"
+ sectionTitle={link ? t('messenger.detail.connections.title') : t('messenger.linq.setupTitle')}
+ onBack={onBack}
+ >
+ {link ? (
+ <UserAgentConnection
+ extraLabel={t('messenger.linq.accountLabel')}
+ link={link}
+ onSetActive={(agentId) => handleSetActive(link.tenantId, agentId)}
+ onUnlink={() => handleUnlink(link.tenantId)}
+ />
+ ) : (
+ <LinqLinkSetup disabled={!canCreate || !canEdit} onLinked={handleLinked} />
+ )}
+ </DetailLayout>
+ );
+});
+
+LinqDetail.displayName = 'MessengerLinqDetail';
+
+export default LinqDetail;
diff --git a/src/features/Messenger/IntegrationDetail/index.tsx b/src/features/Messenger/IntegrationDetail/index.tsx
index f5d99043f7f..68f18ad5fb9 100644
--- a/src/features/Messenger/IntegrationDetail/index.tsx
+++ b/src/features/Messenger/IntegrationDetail/index.tsx
@@ -4,6 +4,7 @@ import { memo } from 'react';
import type { MessengerPlatform } from '../constants';
import DiscordDetail from './Discord';
+import LinqDetail from './Linq';
import SlackDetail from './Slack';
import TelegramDetail from './Telegram';
import WechatDetail from './Wechat';
@@ -36,6 +37,9 @@ const IntegrationDetail = memo<IntegrationDetailProps>(({ platform, ...rest }) =
case 'wechat': {
return <WechatDetail {...rest} />;
}
+ case 'linq': {
+ return <LinqDetail {...rest} />;
+ }
}
});
diff --git a/src/features/Messenger/IntegrationDetail/shared.tsx b/src/features/Messenger/IntegrationDetail/shared.tsx
index 255f2385229..5e56f5b14fe 100644
--- a/src/features/Messenger/IntegrationDetail/shared.tsx
+++ b/src/features/Messenger/IntegrationDetail/shared.tsx
@@ -488,7 +488,9 @@ export const useLinkActions = ({
content:
platform === 'wechat'
? t('messenger.unlinkConfirmWechat')
- : t('messenger.unlinkConfirm', { platform: name }),
+ : platform === 'linq'
+ ? t('messenger.unlinkConfirmLinq')
+ : t('messenger.unlinkConfirm', { platform: name }),
okButtonProps: { danger: true },
onOk: async () => {
try {
diff --git a/src/features/Messenger/constants.tsx b/src/features/Messenger/constants.tsx
index befab07cbbf..665da31eff2 100644
--- a/src/features/Messenger/constants.tsx
+++ b/src/features/Messenger/constants.tsx
@@ -1,17 +1,19 @@
-import { Discord, Slack, Telegram, WeChat } from '@lobehub/ui/icons';
+import { Discord, IMessage, Slack, Telegram, WeChat } from '@lobehub/ui/icons';
import type { ReactNode } from 'react';
-export type MessengerPlatform = 'telegram' | 'slack' | 'discord' | 'wechat';
+export type MessengerPlatform = 'telegram' | 'slack' | 'discord' | 'wechat' | 'linq';
export const SUPPORTED_MESSENGER_PLATFORMS = [
{ id: 'telegram', name: 'Telegram' },
{ id: 'slack', name: 'Slack' },
{ id: 'discord', name: 'Discord' },
{ id: 'wechat', name: 'WeChat' },
+ { id: 'linq', name: 'iMessage' },
] as const satisfies readonly { id: MessengerPlatform; name: string }[];
export const PLATFORM_TAB_ICONS: Record<MessengerPlatform, ReactNode> = {
discord: <Discord.Color size={16} />,
+ linq: <IMessage.Color size={16} />,
slack: <Slack.Color size={16} />,
telegram: <Telegram.Color size={16} />,
wechat: <WeChat.Color size={16} />,
@@ -27,6 +29,7 @@ export const PlatformAvatar = ({
if (platform === 'telegram') return <Telegram.Avatar size={size} />;
if (platform === 'discord') return <Discord.Avatar size={size} />;
if (platform === 'wechat') return <WeChat.Avatar size={size} />;
+ if (platform === 'linq') return <IMessage.Avatar size={size} />;
return <Slack.Avatar size={size} />;
};
@@ -40,6 +43,7 @@ export const PlatformBrandIcon = ({
if (platform === 'telegram') return <Telegram.Color size={size} />;
if (platform === 'discord') return <Discord.Color size={size} />;
if (platform === 'wechat') return <WeChat.Color size={size} />;
+ if (platform === 'linq') return <IMessage.Color size={size} />;
return <Slack.Color size={size} />;
};
diff --git a/src/features/Messenger/index.tsx b/src/features/Messenger/index.tsx
index d8119455de1..c79b96ba8fe 100644
--- a/src/features/Messenger/index.tsx
+++ b/src/features/Messenger/index.tsx
@@ -30,6 +30,7 @@ const VALID_PLATFORMS: ReadonlySet<MessengerPlatform> = new Set([
'telegram',
'discord',
'wechat',
+ 'linq',
]);
const isMessengerPlatform = (value: string | undefined): value is MessengerPlatform =>
diff --git a/src/services/messenger.ts b/src/services/messenger.ts
index 42d6340bceb..3c8f9710bcd 100644
--- a/src/services/messenger.ts
+++ b/src/services/messenger.ts
@@ -2,7 +2,7 @@ import type { MessengerOversizeImageStrategy } from '@lobechat/const';
import { lambdaClient } from '@/libs/trpc/client';
-type MessengerPlatform = 'telegram' | 'slack' | 'discord' | 'wechat';
+type MessengerPlatform = 'telegram' | 'slack' | 'discord' | 'wechat' | 'linq';
class MessengerService {
availablePlatforms = async () => {
@@ -61,6 +61,14 @@ class MessengerService {
return lambdaClient.messenger.pollWechatQrSession.mutate({ sessionId });
};
+ createLinqLink = async () => {
+ return lambdaClient.messenger.createLinqLink.mutate();
+ };
+
+ pollLinqLink = async (pollId: string) => {
+ return lambdaClient.messenger.pollLinqLink.query({ pollId });
+ };
+
getMessengerPushWindow = async (platform: MessengerPlatform, tenantId?: string) => {
return lambdaClient.messenger.getMessengerPushWindow.query({ platform, tenantId });
};