OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
assistant: opt the /ai/agents mount out of Elysia body parsing
Carl-Gerhard Lindesvärdc4beb3020c6b
diff --git a/packages/core/src/modules/assistant/assistant.routes.test.ts b/packages/core/src/modules/assistant/assistant.routes.test.tsnew file mode 100644index 000000000..30fdd97b0--- /dev/null+++ b/packages/core/src/modules/assistant/assistant.routes.test.ts@@ -0,0 +1,78 @@+// The /ai/agents/* mount end to end through `app.handle()`, with the global+// request-logging hook mounted the way apps/api does. That hook references+// `body`, which makes Elysia parse every POST body up front; the route must+// opt out (`parse: 'none'`) or better-agent's own `request.text()` throws+// "Body is disturbed or locked" and every chat run is a 500.++import { beforeEach, expect, mock, test } from 'bun:test';+import { Elysia } from 'elysia';+import { stubAppDeps } from '../../../test/http-fixtures';+import { requestLogging } from '../../http/context';++let session: { userId: string } | null = null;+const resolveSession = mock(() => Promise.resolve(session));+mock.module('../../http/session', () => ({+ SESSION_COOKIE_NAME: 'session',+ resolveSession,+}));++const seenBodies: string[] = [];+mock.module('./assistant.service', () => ({+ createAssistantService: () => ({+ getChatApp: () => ({+ handler: async (request: Request) => {+ seenBodies.push(await request.text());+ return new Response('ok', { status: 200 });+ },+ }),+ getChatRunContext: () => ({+ run: (_context: unknown, fn: () => Promise<Response>) => fn(),+ }),+ }),+}));++const { assistantRoutes } = await import('./assistant.routes');++function buildApp() {+ const { deps } = stubAppDeps();+ return new Elysia().use(requestLogging(deps)).use(assistantRoutes(deps));+}++let app: ReturnType<typeof buildApp>;++beforeEach(() => {+ app = buildApp();+ session = { userId: 'user_1' };+ seenBodies.length = 0;+});++function post(path: string, body: unknown) {+ return app.handle(+ new Request(`http://localhost${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', cookie: 'session=s' },+ body: JSON.stringify(body),+ })+ );+}++test('hands the chat app an unread body even with the global logging hook mounted', async () => {+ const body = { agent: '__titler', input: 'hi' };+ const response = await post('/ai/agents/__titler/run', body);+ expect(response.status).toBe(200);+ expect(seenBodies).toEqual([JSON.stringify(body)]);+});++test('a run without project context is a 400, not a body error', async () => {+ const response = await post('/ai/agents/gpt/run', { input: 'hi' });+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toEqual({+ message: 'Missing projectId or organizationId in context',+ });+});++test('no session -> 401', async () => {+ session = null;+ const response = await post('/ai/agents/__titler/run', { input: 'hi' });+ expect(response.status).toBe(401);+});diff --git a/packages/core/src/modules/assistant/assistant.routes.ts b/packages/core/src/modules/assistant/assistant.routes.tsindex c50d614bf..2a35472cb 100644--- a/packages/core/src/modules/assistant/assistant.routes.ts+++ b/packages/core/src/modules/assistant/assistant.routes.ts@@ -4,9 +4,13 @@// Elysia has no adapter in `@better-agent/adapters` (only express/fastify),// but `BetterAgentApp.handler` already speaks the Web `Request`/`Response`// pair Elysia's own handlers do, so this route calls it directly instead of-// waiting on one. The request body is read via `request.clone()` for the-// project-access check below — `chatApp.handler` gets the original,-// unconsumed `request` so it can re-read the body itself.+// waiting on one. `parse: 'none'` is load-bearing, as on the /trpc mount in+// apps/api/src/main.ts: the global request-logging hook references `body`,+// which makes Elysia infer body parsing for every route and consume the+// stream before the handler runs; `request.clone()` then throws "Body is+// disturbed or locked". With parsing off, the body is read via+// `request.clone()` for the project-access check below and `chatApp.handler`+// gets the original, unconsumed `request` so it can re-read it itself.//// M15-003: this route is where `deps` lives, so everything below it reaches// Postgres/ClickHouse through `ctx` — the chat app, the conversation lookup@@ -103,6 +107,6 @@ export const assistantRoutes = defineRoutes((app) =>() => chatApp.handler(request));},- { session: true, detail: { hide: true } }+ { session: true, detail: { hide: true }, parse: 'none' }));