chat-route.test.ts
1 import assert from 'node:assert/strict' 2 import test from 'node:test' 3 4 import { runWithTempDataDir } from '@/lib/server/test-utils/run-with-temp-data-dir' 5 6 test('chat route rejects malformed JSON with a 400 before queueing work', () => { 7 const output = runWithTempDataDir<{ 8 status: number 9 payload: { error?: string } 10 runCount: number 11 }>(` 12 const storageMod = await import('./src/lib/server/storage') 13 const routeMod = await import('./src/app/api/chats/[id]/chat/route') 14 const runsMod = await import('@/lib/server/runtime/session-run-manager') 15 const storage = storageMod.default || storageMod 16 const route = routeMod.default || routeMod 17 const runs = runsMod.default || runsMod 18 19 const now = Date.now() 20 storage.saveAgents({ 21 agent_1: { 22 id: 'agent_1', 23 name: 'Malformed Agent', 24 provider: 'openai', 25 model: 'gpt-4o-mini', 26 extensions: [], 27 createdAt: now, 28 updatedAt: now, 29 }, 30 }) 31 storage.saveSessions({ 32 sess_1: { 33 id: 'sess_1', 34 name: 'Malformed Session', 35 cwd: process.env.WORKSPACE_DIR, 36 user: 'workbench', 37 provider: 'openai', 38 model: 'gpt-4o-mini', 39 claudeSessionId: null, 40 messages: [], 41 createdAt: now, 42 lastActiveAt: now, 43 sessionType: 'human', 44 agentId: 'agent_1', 45 extensions: [], 46 }, 47 }) 48 49 const response = await route.POST( 50 new Request('http://local/api/chats/sess_1/chat', { 51 method: 'POST', 52 headers: { 'content-type': 'application/json' }, 53 body: '{bad-json', 54 }), 55 { params: Promise.resolve({ id: 'sess_1' }) }, 56 ) 57 58 console.log(JSON.stringify({ 59 status: response.status, 60 payload: await response.json(), 61 runCount: runs.listRuns({ sessionId: 'sess_1' }).length, 62 })) 63 `, { prefix: 'swarmclaw-chat-route-invalid-json-' }) 64 65 assert.equal(output.status, 400) 66 assert.equal(output.payload.error, 'Invalid or missing request body') 67 assert.equal(output.runCount, 0) 68 })