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: add agent hono routes (#14535)

Rdmclin2507909dc2caa
diff --git a/src/app/(backend)/api/agent/messenger/[platform]/install/route.test.ts b/src/server/agent-hono/handlers/__tests__/messengerInstall.test.ts
similarity index 75%
rename from src/app/(backend)/api/agent/messenger/[platform]/install/route.test.ts
rename to src/server/agent-hono/handlers/__tests__/messengerInstall.test.ts
index 66034df9954..51afaf51b93 100644
--- a/src/app/(backend)/api/agent/messenger/[platform]/install/route.test.ts
+++ b/src/server/agent-hono/handlers/__tests__/messengerInstall.test.ts
@@ -1,10 +1,11 @@
// @vitest-environment node
+import type { Context } from 'hono';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { auth } from '@/auth';
import { issueOAuthState } from '@/server/services/messenger/oauth/stateStore';
-import { GET } from './route';
+import { messengerInstall } from '../messengerInstall';
vi.mock('@/auth', () => ({
auth: {
@@ -43,8 +44,17 @@ const VALID_DISCORD_CONFIG = {
publicKey: 'pubkey',
};
-const buildRequest = (path: string): Request => new Request(`https://app.example.com${path}`);
-const ctx = (platform: string) => ({ params: Promise.resolve({ platform }) });
+const buildContext = (platform: string, path: string): Context => {
+ const raw = new Request(`https://app.example.com${path}`);
+ return {
+ json: (b: any, status = 200) => Response.json(b, { status }),
+ req: {
+ param: (name: string) => (name === 'platform' ? platform : undefined),
+ raw,
+ url: raw.url,
+ },
+ } as any;
+};
beforeEach(() => {
vi.mocked(auth.api.getSession).mockResolvedValue({
@@ -60,15 +70,19 @@ afterEach(() => {
vi.clearAllMocks();
});
-describe('GET /api/agent/messenger/[platform]/install', () => {
+describe('GET /api/agent/messenger/:platform/install', () => {
describe('platform routing', () => {
it('404s for an unknown platform', async () => {
- const res = await GET(buildRequest('/api/agent/messenger/unknown/install'), ctx('unknown'));
+ const res = await messengerInstall(
+ buildContext('unknown', '/api/agent/messenger/unknown/install'),
+ );
expect(res.status).toBe(404);
});
it('404s for a known platform that has no OAuth adapter (telegram)', async () => {
- const res = await GET(buildRequest('/api/agent/messenger/telegram/install'), ctx('telegram'));
+ const res = await messengerInstall(
+ buildContext('telegram', '/api/agent/messenger/telegram/install'),
+ );
expect(res.status).toBe(404);
});
});
@@ -77,7 +91,9 @@ describe('GET /api/agent/messenger/[platform]/install', () => {
it('redirects unauthenticated users to /signin with callbackUrl', async () => {
vi.mocked(auth.api.getSession).mockResolvedValue(null);
- const res = await GET(buildRequest('/api/agent/messenger/slack/install'), ctx('slack'));
+ const res = await messengerInstall(
+ buildContext('slack', '/api/agent/messenger/slack/install'),
+ );
expect(res.status).toBe(302);
const parsed = new URL(res.headers.get('location')!);
expect(parsed.pathname).toBe('/signin');
@@ -87,13 +103,17 @@ describe('GET /api/agent/messenger/[platform]/install', () => {
it('returns 503 when Slack OAuth env is not configured', async () => {
vi.mocked(getMessengerSlackConfig).mockResolvedValue(null);
- const res = await GET(buildRequest('/api/agent/messenger/slack/install'), ctx('slack'));
+ const res = await messengerInstall(
+ buildContext('slack', '/api/agent/messenger/slack/install'),
+ );
expect(res.status).toBe(503);
expect(await res.text()).toMatch(/Slack messenger is not configured/);
});
it('issues a state token bound to the LobeHub user and 302s to Slack authorize', async () => {
- const res = await GET(buildRequest('/api/agent/messenger/slack/install'), ctx('slack'));
+ const res = await messengerInstall(
+ buildContext('slack', '/api/agent/messenger/slack/install'),
+ );
expect(res.status).toBe(302);
expect(issueOAuthState).toHaveBeenCalledWith({
@@ -113,9 +133,8 @@ describe('GET /api/agent/messenger/[platform]/install', () => {
});
it('forwards returnTo into the state payload when provided', async () => {
- await GET(
- buildRequest('/api/agent/messenger/slack/install?returnTo=/settings/messenger'),
- ctx('slack'),
+ await messengerInstall(
+ buildContext('slack', '/api/agent/messenger/slack/install?returnTo=/settings/messenger'),
);
expect(issueOAuthState).toHaveBeenCalledWith({
lobeUserId: 'lobe-user-1',
@@ -131,13 +150,17 @@ describe('GET /api/agent/messenger/[platform]/install', () => {
clientSecret: undefined,
});
- const res = await GET(buildRequest('/api/agent/messenger/discord/install'), ctx('discord'));
+ const res = await messengerInstall(
+ buildContext('discord', '/api/agent/messenger/discord/install'),
+ );
expect(res.status).toBe(503);
expect(await res.text()).toMatch(/Discord messenger is not configured/);
});
it('302s to discord.com authorize with bot scope and permissions', async () => {
- const res = await GET(buildRequest('/api/agent/messenger/discord/install'), ctx('discord'));
+ const res = await messengerInstall(
+ buildContext('discord', '/api/agent/messenger/discord/install'),
+ );
expect(res.status).toBe(302);
const parsed = new URL(res.headers.get('location')!);
expect(parsed.origin + parsed.pathname).toBe('https://discord.com/api/oauth2/authorize');
diff --git a/src/app/(backend)/api/agent/messenger/[platform]/oauth/callback/route.test.ts b/src/server/agent-hono/handlers/__tests__/messengerOAuthCallback.test.ts
similarity index 86%
rename from src/app/(backend)/api/agent/messenger/[platform]/oauth/callback/route.test.ts
rename to src/server/agent-hono/handlers/__tests__/messengerOAuthCallback.test.ts
index d23526d4b16..7ff055a34ac 100644
--- a/src/app/(backend)/api/agent/messenger/[platform]/oauth/callback/route.test.ts
+++ b/src/server/agent-hono/handlers/__tests__/messengerOAuthCallback.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import type { Context } from 'hono';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MessengerInstallationModel } from '@/database/models/messengerInstallation';
@@ -6,7 +7,7 @@ import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { exchangeCode } from '@/server/services/messenger/oauth/slackOAuth';
import { consumeOAuthState } from '@/server/services/messenger/oauth/stateStore';
-import { GET } from './route';
+import { messengerOAuthCallback } from '../messengerOAuthCallback';
vi.mock('@/database/core/db-adaptor', () => ({
getServerDB: vi.fn().mockResolvedValue({}),
@@ -58,9 +59,19 @@ const VALID_DISCORD_CONFIG = {
publicKey: 'pubkey',
};
-const buildRequest = (platform: string, qs: string): Request =>
- new Request(`https://app.example.com/api/agent/messenger/${platform}/oauth/callback?${qs}`);
-const ctx = (platform: string) => ({ params: Promise.resolve({ platform }) });
+const buildContext = (platform: string, qs: string): Context => {
+ const raw = new Request(
+ `https://app.example.com/api/agent/messenger/${platform}/oauth/callback?${qs}`,
+ );
+ return {
+ json: (b: any, status = 200) => Response.json(b, { status }),
+ req: {
+ param: (name: string) => (name === 'platform' ? platform : undefined),
+ raw,
+ url: raw.url,
+ },
+ } as any;
+};
beforeEach(() => {
vi.mocked(getMessengerSlackConfig).mockResolvedValue(VALID_SLACK_CONFIG);
@@ -84,22 +95,22 @@ afterEach(() => {
vi.clearAllMocks();
});
-describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
+describe('GET /api/agent/messenger/:platform/oauth/callback', () => {
describe('platform routing', () => {
it('404s for an unknown platform', async () => {
- const res = await GET(buildRequest('unknown', 'code=c&state=s'), ctx('unknown'));
+ const res = await messengerOAuthCallback(buildContext('unknown', 'code=c&state=s'));
expect(res.status).toBe(404);
});
it('404s for telegram (no OAuth adapter)', async () => {
- const res = await GET(buildRequest('telegram', 'code=c&state=s'), ctx('telegram'));
+ const res = await messengerOAuthCallback(buildContext('telegram', 'code=c&state=s'));
expect(res.status).toBe(404);
});
});
describe('slack β€” error / validation paths', () => {
it('redirects to settings with error when the upstream returned ?error=', async () => {
- const res = await GET(buildRequest('slack', 'error=access_denied'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'error=access_denied'));
expect(res.status).toBe(302);
const loc = new URL(res.headers.get('location')!);
expect(loc.pathname).toBe('/settings/messenger/slack');
@@ -107,7 +118,7 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
});
it('redirects to settings with missing_code_or_state when params are absent', async () => {
- const res = await GET(buildRequest('slack', ''), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', ''));
expect(res.status).toBe(302);
const loc = new URL(res.headers.get('location')!);
expect(loc.pathname).toBe('/settings/messenger/slack');
@@ -116,13 +127,13 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
it('returns 503 when Slack messenger env is not configured', async () => {
vi.mocked(getMessengerSlackConfig).mockResolvedValue(null);
- const res = await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
expect(res.status).toBe(503);
});
it('redirects with invalid_state when the state token has expired or never existed', async () => {
vi.mocked(consumeOAuthState).mockResolvedValue(null);
- const res = await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
expect(res.status).toBe(302);
const loc = new URL(res.headers.get('location')!);
expect(loc.searchParams.get('error')).toBe('invalid_state');
@@ -130,7 +141,7 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
it('redirects with exchange_failed when oauth.v2.access throws', async () => {
vi.mocked(exchangeCode).mockRejectedValue(new Error('upstream 502'));
- const res = await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
expect(res.status).toBe(302);
const loc = new URL(res.headers.get('location')!);
expect(loc.searchParams.get('error')).toBe('exchange_failed');
@@ -144,7 +155,7 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
ok: true,
team: null,
});
- const res = await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
expect(res.status).toBe(302);
const loc = new URL(res.headers.get('location')!);
// missing_tenant is mapped to exchange_failed at the route level since
@@ -155,7 +166,9 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
describe('slack β€” happy path: workspace install', () => {
it('persists the installation and redirects to slack.com/app/open', async () => {
- const res = await GET(buildRequest('slack', 'code=the-code&state=the-state'), ctx('slack'));
+ const res = await messengerOAuthCallback(
+ buildContext('slack', 'code=the-code&state=the-state'),
+ );
expect(consumeOAuthState).toHaveBeenCalledWith('the-state');
expect(exchangeCode).toHaveBeenCalledWith({
@@ -202,7 +215,7 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
team: { id: 'T_ROT', name: 'Rotating' },
});
- await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
const upsertCall = vi.mocked(MessengerInstallationModel.upsert).mock.calls.at(-1)!;
const params = upsertCall[1];
@@ -229,7 +242,7 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
it('refreshes credentials but preserves the original owner, then redirects with already_installed', async () => {
vi.mocked(MessengerInstallationModel.findByTenant).mockResolvedValue(existingInstall);
- const res = await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
expect(MessengerInstallationModel.upsert).toHaveBeenCalledWith(
expect.anything(),
@@ -255,7 +268,7 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
installedByUserId: null,
});
- const res = await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
expect(MessengerInstallationModel.upsert).toHaveBeenCalledWith(
expect.anything(),
@@ -273,7 +286,7 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
installedByUserId: 'lobe-user-1',
});
- const res = await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
expect(MessengerInstallationModel.upsert).toHaveBeenCalledWith(
expect.anything(),
@@ -298,7 +311,7 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
team: null,
});
- const res = await GET(buildRequest('slack', 'code=c&state=s'), ctx('slack'));
+ const res = await messengerOAuthCallback(buildContext('slack', 'code=c&state=s'));
const upsertCall = vi.mocked(MessengerInstallationModel.upsert).mock.calls.at(-1)!;
const params = upsertCall[1];
@@ -347,9 +360,8 @@ describe('GET /api/agent/messenger/[platform]/oauth/callback', () => {
});
it('persists the installation and falls back to settings (no deep link for discord)', async () => {
- const res = await GET(
- buildRequest('discord', 'code=the-code&state=the-state'),
- ctx('discord'),
+ const res = await messengerOAuthCallback(
+ buildContext('discord', 'code=the-code&state=the-state'),
);
expect(fetchMock).toHaveBeenCalledWith(
diff --git a/src/app/(backend)/api/agent/messenger/[platform]/install/route.ts b/src/server/agent-hono/handlers/messengerInstall.ts
similarity index 92%
rename from src/app/(backend)/api/agent/messenger/[platform]/install/route.ts
rename to src/server/agent-hono/handlers/messengerInstall.ts
index 33dc08f2614..232a195a95d 100644
--- a/src/app/(backend)/api/agent/messenger/[platform]/install/route.ts
+++ b/src/server/agent-hono/handlers/messengerInstall.ts
@@ -1,4 +1,5 @@
import debug from 'debug';
+import type { Context } from 'hono';
import { auth } from '@/auth';
import { appEnv } from '@/envs/app';
@@ -23,11 +24,13 @@ const log = debug('lobe-server:messenger:install');
* public Marketplace deep link, so the install row is bound to a real user
* end-to-end.
*/
-export const GET = async (
- req: Request,
- { params }: { params: Promise<{ platform: string }> },
-): Promise<Response> => {
- const { platform } = await params;
+export async function messengerInstall(c: Context): Promise<Response> {
+ const platform = c.req.param('platform');
+ if (!platform) {
+ return c.json({ error: 'platform is required' }, 400);
+ }
+
+ const req = c.req.raw;
const url = new URL(req.url);
// 1. Platform definition must exist and expose an OAuth adapter.
@@ -84,4 +87,4 @@ export const GET = async (
log('install: redirecting user=%s to %s authorize', session.user.id, platform);
return Response.redirect(authorizeUrl, 302);
-};
+}
diff --git a/src/app/(backend)/api/agent/messenger/[platform]/oauth/callback/route.ts b/src/server/agent-hono/handlers/messengerOAuthCallback.ts
similarity index 96%
rename from src/app/(backend)/api/agent/messenger/[platform]/oauth/callback/route.ts
rename to src/server/agent-hono/handlers/messengerOAuthCallback.ts
index 35f5eaa5ca3..ede5473ca38 100644
--- a/src/app/(backend)/api/agent/messenger/[platform]/oauth/callback/route.ts
+++ b/src/server/agent-hono/handlers/messengerOAuthCallback.ts
@@ -1,4 +1,5 @@
import debug from 'debug';
+import type { Context } from 'hono';
import { getServerDB } from '@/database/core/db-adaptor';
import { MessengerInstallationModel } from '@/database/models/messengerInstallation';
@@ -41,12 +42,13 @@ const errorRedirect = (origin: string, platform: string, code: string, extra?: U
* 5. Hand off to the platform's deep-link redirect (Slack
* `slack.com/app/open`) or fall back to the settings page.
*/
-export const GET = async (
- req: Request,
- { params }: { params: Promise<{ platform: string }> },
-): Promise<Response> => {
- const { platform } = await params;
- const url = new URL(req.url);
+export async function messengerOAuthCallback(c: Context): Promise<Response> {
+ const platform = c.req.param('platform');
+ if (!platform) {
+ return c.json({ error: 'platform is required' }, 400);
+ }
+
+ const url = new URL(c.req.url);
const definition = messengerPlatformRegistry.getPlatform(platform);
if (!definition?.oauth) {
@@ -201,4 +203,4 @@ export const GET = async (
}
return redirectToPlatform(url.origin, platform, 'installed=ok');
-};
+}
diff --git a/src/app/(backend)/api/agent/messenger/webhooks/[platform]/route.ts b/src/server/agent-hono/handlers/messengerWebhook.ts
similarity index 64%
rename from src/app/(backend)/api/agent/messenger/webhooks/[platform]/route.ts
rename to src/server/agent-hono/handlers/messengerWebhook.ts
index c26a07bd515..85dd1c1a07d 100644
--- a/src/app/(backend)/api/agent/messenger/webhooks/[platform]/route.ts
+++ b/src/server/agent-hono/handlers/messengerWebhook.ts
@@ -1,4 +1,5 @@
import debug from 'debug';
+import type { Context } from 'hono';
import { getMessengerRouter } from '@/server/services/messenger';
@@ -7,22 +8,23 @@ const log = debug('lobe-server:messenger:webhook-route');
/**
* Webhook endpoint for the shared Messenger bot.
*
- * Distinct from `/api/agent/webhooks/[platform]/[appId]` which routes per-user
+ * Distinct from `/api/agent/webhooks/:platform/:appId` which routes per-user
* Bot Channels by `applicationId`. Here, the bot is global per platform with
* credentials in env, and routing is by message sender β†’ linked agent.
*
* - POST /api/agent/messenger/webhooks/telegram
* - POST /api/agent/messenger/webhooks/slack (planned)
*/
-export const POST = async (
- req: Request,
- { params }: { params: Promise<{ platform: string }> },
-): Promise<Response> => {
- const { platform } = await params;
+export async function messengerWebhook(c: Context): Promise<Response> {
+ const platform = c.req.param('platform');
- log('Received messenger webhook: platform=%s, url=%s', platform, req.url);
+ if (!platform) {
+ return c.json({ error: 'platform is required' }, 400);
+ }
+
+ log('Received messenger webhook: platform=%s, url=%s', platform, c.req.url);
const router = getMessengerRouter();
const handler = router.getWebhookHandler(platform);
- return handler(req);
-};
+ return handler(c.req.raw);
+}
diff --git a/src/server/agent-hono/index.ts b/src/server/agent-hono/index.ts
index 0ac3b0dbaeb..aefcb8f793a 100644
--- a/src/server/agent-hono/index.ts
+++ b/src/server/agent-hono/index.ts
@@ -6,6 +6,9 @@ import { finalizeAbandoned } from './handlers/finalizeAbandoned';
import { gatewayCallback } from './handlers/gatewayCallback';
import { gatewayCron } from './handlers/gatewayCron';
import { gatewayStart } from './handlers/gatewayStart';
+import { messengerInstall } from './handlers/messengerInstall';
+import { messengerOAuthCallback } from './handlers/messengerOAuthCallback';
+import { messengerWebhook } from './handlers/messengerWebhook';
import { platformWebhook } from './handlers/platformWebhook';
import { runStep, runStepHealth } from './handlers/runStep';
import { toolResult } from './handlers/toolResult';
@@ -68,4 +71,13 @@ app.post('/webhooks/bot-callback', qstashAuth(), botCallback);
// POST /api/agent/webhooks/:platform[/:appId] β€” Chat SDK bot platform webhooks
app.post('/webhooks/:platform/:appId?', platformWebhook);
+// GET /api/agent/messenger/:platform/install β€” start per-tenant OAuth install
+app.get('/messenger/:platform/install', messengerInstall);
+
+// GET /api/agent/messenger/:platform/oauth/callback β€” OAuth redirect target
+app.get('/messenger/:platform/oauth/callback', messengerOAuthCallback);
+
+// POST /api/agent/messenger/webhooks/:platform β€” shared Messenger bot webhook
+app.post('/messenger/webhooks/:platform', messengerWebhook);
+
export default app;