Files
Codeman/test/routes/case-routes.test.ts
T
arkonandClaude Opus 4.8 458fb81cbe feat(api): establish stable HTTP contract — uniform {success,data} envelope, status codes, /api/v1
Point 1 of the v1.0 lock-in: commit to a stable HTTP API (the cleanest, fullest form).

Core (centralized):
- Every JSON /api response now uses ONE envelope via a Fastify preSerialization hook (src/web/server.ts): success -> { success:true, data:<payload> }; error -> { success:false, error, errorCode } with a conventional HTTP status. Non-JSON routes (file-raw, tail-file SSE, download, screenshots, /q redirect, WS) are skipped.
- Error-code -> HTTP status is a single source of truth (httpStatusForErrorCode in src/types/api.ts): 400/401/404/409/422/429/500. Expanded ApiErrorCode (added UNAUTHORIZED, CONFLICT, RATE_LIMITED). Errors are no longer HTTP 200.
- Versioned alias: /api/v1/* rewrites to /api/* (rewriteApiV1Url), so external clients pin to a stable surface while the bundled UI keeps using /api/*.
- Handlers stripped of manual 'success:true' (50 across 14 route files) so they return bare payloads the hook wraps uniformly; fixed the mux DELETE {success:<bool>} envelope collision (-> {killed}).

Frontend (48 call sites across 10 files):
- _apiJson() auto-unwraps { success:true, data } -> data (null on error), so most bare-shape readers are transparent. Raw-fetch sites relocate payload reads under .data; success/res.ok/error checks unchanged.

Docs: new docs/api-reference.md (envelope, status table, error codes, /api/v1, SSE); versioning-policy.md flipped — the HTTP/SSE API is now part of the stable, SemVer-covered surface.

Verification: full unit/route suite green (2680 passed) incl. ~166 updated assertions across 24 test files; typecheck/lint/format/frontend-syntax clean; a headless-chromium smoke loaded the migrated UI and drove the panels with 0 console/page errors; /api/status and /api/v1/status confirmed returning the uniform envelope live.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 01:30:43 +02:00

571 lines
20 KiB
TypeScript

/**
* @fileoverview Tests for case-routes route handlers.
*
* Uses app.inject() — no real HTTP ports needed.
* Port: N/A (app.inject doesn't open ports)
*
* Responses follow the uniform envelope contract:
* SUCCESS -> HTTP 2xx, body = { success: true, data: <payload> }
* ERROR -> HTTP 4xx/5xx, body = { success: false, error, errorCode }
* Bare handler returns are wrapped into { success:true, data } and returned
* error envelopes are mapped to their conventional HTTP status by the same
* preSerialization hook the production server installs (mirrored below so test
* behavior matches production exactly).
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { ApiErrorCode, httpStatusForErrorCode } from '../../src/types.js';
import { registerCaseRoutes } from '../../src/web/routes/case-routes.js';
// Mock filesystem modules
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
return {
...actual,
existsSync: vi.fn(() => false),
mkdirSync: vi.fn(),
writeFileSync: vi.fn(),
readdirSync: vi.fn(() => []),
};
});
vi.mock('node:fs/promises', () => ({
default: {
readdir: vi.fn(async () => []),
readFile: vi.fn(async () => {
const err = new Error('ENOENT') as NodeJS.ErrnoException;
err.code = 'ENOENT';
throw err;
}),
writeFile: vi.fn(async () => {}),
},
}));
vi.mock('../../src/templates/claude-md.js', () => ({
generateClaudeMd: vi.fn(() => '# CLAUDE.md\nGenerated content'),
}));
vi.mock('../../src/hooks-config.js', () => ({
writeHooksConfig: vi.fn(async () => {}),
}));
// Import mocked modules for test control
import { existsSync, mkdirSync, readdirSync } from 'node:fs';
import fs from 'node:fs/promises';
const mockedExistsSync = vi.mocked(existsSync);
const mockedMkdirSync = vi.mocked(mkdirSync);
const mockedReaddirSync = vi.mocked(readdirSync);
const mockedReaddir = vi.mocked(fs.readdir);
const mockedReadFile = vi.mocked(fs.readFile);
interface CaseRouteHarness {
app: FastifyInstance;
ctx: MockRouteContext;
}
/**
* Build a route harness that mirrors production: cookie plugin, the shared
* route error handler, AND the uniform-envelope preSerialization hook (copied
* from src/web/server.ts) so bare handler returns become { success:true, data }
* and returned error envelopes get mapped to a conventional HTTP status.
*/
async function createEnvelopeHarness(): Promise<CaseRouteHarness> {
const app = Fastify({ logger: false });
await app.register(fastifyCookie);
// Uniform response envelope (matches src/web/server.ts preSerialization hook).
app.addHook('preSerialization', (req, reply, payload: unknown, done) => {
if (!req.url.startsWith('/api')) return done(null, payload);
if (payload === null || typeof payload !== 'object') return done(null, payload);
if (Buffer.isBuffer(payload) || typeof (payload as { pipe?: unknown }).pipe === 'function') {
return done(null, payload);
}
const p = payload as { success?: unknown; errorCode?: unknown };
if (p.success === false) {
if (reply.statusCode === 200 && typeof p.errorCode === 'string') {
reply.code(httpStatusForErrorCode(p.errorCode as ApiErrorCode));
}
return done(null, payload);
}
if (p.success === true) return done(null, payload);
return done(null, { success: true, data: payload });
});
const ctx = createMockRouteContext();
registerCaseRoutes(app, ctx as never);
installRouteErrorHandler(app);
await app.ready();
return { app, ctx };
}
describe('case-routes', () => {
let harness: CaseRouteHarness;
beforeEach(async () => {
harness = await createEnvelopeHarness();
vi.clearAllMocks();
// Default: existsSync returns false, readFile throws ENOENT
mockedExistsSync.mockReturnValue(false);
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
});
afterEach(async () => {
await harness.app.close();
});
// ========== GET /api/cases ==========
describe('GET /api/cases', () => {
it('returns empty array when no cases exist', async () => {
mockedReaddir.mockRejectedValue(new Error('ENOENT'));
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data).toEqual([]);
});
it('returns cases from CASES_DIR', async () => {
mockedReaddir.mockResolvedValue([
{ name: 'my-case', isDirectory: () => true },
{ name: 'other-case', isDirectory: () => true },
{ name: 'readme.txt', isDirectory: () => false },
] as never);
// No CLAUDE.md exists
mockedExistsSync.mockReturnValue(false);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.data).toHaveLength(2);
expect(body.data[0].name).toBe('my-case');
expect(body.data[1].name).toBe('other-case');
expect(body.data[0].hasClaudeMd).toBe(false);
});
it('includes hasClaudeMd flag', async () => {
mockedReaddir.mockResolvedValue([{ name: 'case-with-md', isDirectory: () => true }] as never);
mockedExistsSync.mockReturnValue(true);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.data[0].hasClaudeMd).toBe(true);
});
it('includes linked cases from linked-cases.json', async () => {
// CASES_DIR readdir returns one case
mockedReaddir.mockResolvedValue([{ name: 'regular-case', isDirectory: () => true }] as never);
// linked-cases.json is read second (after CASES_DIR readdir)
let readCallCount = 0;
mockedReadFile.mockImplementation(async () => {
readCallCount++;
if (readCallCount === 1) {
return JSON.stringify({ 'linked-project': '/home/user/projects/linked' });
}
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
});
// existsSync: path exists for linked case, CLAUDE.md check
mockedExistsSync.mockImplementation((p: string) => {
if (typeof p === 'string' && p.includes('linked')) return true;
return false;
});
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
// Should have both regular and linked cases
expect(body.data.length).toBeGreaterThanOrEqual(1);
});
});
// ========== POST /api/cases ==========
describe('POST /api/cases', () => {
it('rejects invalid case name', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases',
payload: { name: 'invalid case name!!' },
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('rejects missing name', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases',
payload: {},
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('rejects path traversal in name', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases',
payload: { name: '../etc' },
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('rejects duplicate case name', async () => {
mockedExistsSync.mockReturnValue(true);
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases',
payload: { name: 'existing-case' },
});
expect(res.statusCode).toBe(409);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
expect(body.error).toContain('already exists');
});
it('creates case directory with CLAUDE.md and hooks config', async () => {
mockedExistsSync.mockReturnValue(false);
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases',
payload: { name: 'new-case', description: 'A new test case' },
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.case.name).toBe('new-case');
expect(body.data.case.path).toContain('new-case');
// Verify directory creation
expect(mockedMkdirSync).toHaveBeenCalled();
// Verify broadcast
expect(harness.ctx.broadcast).toHaveBeenCalledWith('case:created', expect.objectContaining({ name: 'new-case' }));
});
});
// ========== POST /api/cases/link ==========
describe('POST /api/cases/link', () => {
it('rejects invalid request body', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases/link',
payload: { name: 'bad name!' },
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('rejects missing fields', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases/link',
payload: {},
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('returns not found when folder does not exist', async () => {
mockedExistsSync.mockReturnValue(false);
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases/link',
payload: { name: 'my-project', path: '/nonexistent/path' },
});
expect(res.statusCode).toBe(404);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
expect(body.error).toContain('not found');
});
it('rejects when case name already exists in CASES_DIR', async () => {
// First call (expandedPath check) returns true, second (casePath check) also returns true
mockedExistsSync.mockReturnValue(true);
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases/link',
payload: { name: 'existing-case', path: '/home/user/project' },
});
expect(res.statusCode).toBe(409);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
expect(body.error).toContain('already exists');
});
it('links folder successfully', async () => {
// expandedPath exists (first call), casePath does not (second call)
let callIdx = 0;
mockedExistsSync.mockImplementation(() => {
callIdx++;
return callIdx === 1; // first: folder exists, second: case dir doesn't
});
// linked-cases.json doesn't exist yet
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
const res = await harness.app.inject({
method: 'POST',
url: '/api/cases/link',
payload: { name: 'linked-project', path: '/home/user/project' },
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.case.name).toBe('linked-project');
expect(harness.ctx.broadcast).toHaveBeenCalledWith(
'case:linked',
expect.objectContaining({ name: 'linked-project' })
);
});
});
// ========== GET /api/cases/:name ==========
describe('GET /api/cases/:name', () => {
it('returns linked case info', async () => {
mockedReadFile.mockResolvedValue(JSON.stringify({ 'my-case': '/home/user/my-case' }) as never);
mockedExistsSync.mockReturnValue(true);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.name).toBe('my-case');
expect(body.data.linked).toBe(true);
});
it('returns CASES_DIR case when no linked case found', async () => {
// linked-cases.json read fails
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
// case dir exists
mockedExistsSync.mockReturnValue(true);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/regular-case',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.name).toBe('regular-case');
});
it('returns error when case not found anywhere', async () => {
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
mockedExistsSync.mockReturnValue(false);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/nonexistent',
});
expect(res.statusCode).toBe(404);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
expect(body.error).toContain('not found');
});
});
// ========== GET /api/cases/:name/fix-plan ==========
describe('GET /api/cases/:name/fix-plan', () => {
it('returns exists=false when no fix plan file', async () => {
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
mockedExistsSync.mockReturnValue(false);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case/fix-plan',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.exists).toBe(false);
expect(body.data.content).toBeNull();
expect(body.data.todos).toEqual([]);
});
it('parses fix plan with todos and stats', async () => {
const fixPlanContent = [
'# Fix Plan',
'## High Priority',
'- [ ] Fix critical bug',
'- [-] Working on auth',
'- [x] Setup database',
'## Standard',
'- [ ] Add logging',
'## Completed',
'- [x] Initial setup',
].join('\n');
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
mockedExistsSync.mockImplementation((p: string) => {
if (typeof p === 'string' && p.includes('fix_plan')) return true;
return false;
});
// Override readFile for the fix plan read
mockedReadFile.mockImplementation(async (p: string) => {
if (typeof p === 'string' && p.includes('fix_plan')) {
return fixPlanContent as never;
}
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
});
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case/fix-plan',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.exists).toBe(true);
expect(body.data.todos.length).toBeGreaterThan(0);
expect(body.data.stats.total).toBeGreaterThan(0);
});
});
// ========== GET /api/cases/:caseName/ralph-wizard/files ==========
describe('GET /api/cases/:caseName/ralph-wizard/files', () => {
it('returns error when wizard directory not found', async () => {
mockedExistsSync.mockReturnValue(false);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case/ralph-wizard/files',
});
expect(res.statusCode).toBe(404);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
expect(body.error).toContain('not found');
});
it('rejects path traversal in case name', async () => {
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/..%2F..%2Fetc/ralph-wizard/files',
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('returns wizard files when directory exists', async () => {
mockedExistsSync.mockImplementation((p: string) => {
if (typeof p === 'string' && p.includes('ralph-wizard')) return true;
if (typeof p === 'string' && p.includes('prompt.md')) return true;
if (typeof p === 'string' && p.includes('result.json')) return true;
return false;
});
mockedReaddirSync.mockReturnValue([
{ name: 'research', isDirectory: () => true },
{ name: 'planner', isDirectory: () => true },
] as never);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case/ralph-wizard/files',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.files).toHaveLength(2);
expect(body.data.files[0].agentType).toBe('research');
});
});
// ========== GET /api/cases/:caseName/ralph-wizard/file/:filePath ==========
describe('GET /api/cases/:caseName/ralph-wizard/file/:filePath', () => {
it('returns error for missing file', async () => {
mockedExistsSync.mockReturnValue(false);
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case/ralph-wizard/file/research%2Fprompt.md',
});
expect(res.statusCode).toBe(404);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('returns markdown file content', async () => {
mockedExistsSync.mockReturnValue(false);
mockedReadFile.mockResolvedValue('# Research Prompt\nContent here' as never);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case/ralph-wizard/file/research%2Fprompt.md',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.content).toContain('Research Prompt');
expect(body.data.isJson).toBe(false);
});
it('parses JSON file content', async () => {
mockedExistsSync.mockReturnValue(false);
const jsonContent = JSON.stringify({ plan: 'test plan', steps: [1, 2, 3] });
mockedReadFile.mockResolvedValue(jsonContent as never);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case/ralph-wizard/file/planner%2Fresult.json',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(true);
expect(body.data.isJson).toBe(true);
expect(body.data.parsed.plan).toBe('test plan');
});
it('sets no-cache headers', async () => {
mockedExistsSync.mockReturnValue(false);
mockedReadFile.mockResolvedValue('content' as never);
const res = await harness.app.inject({
method: 'GET',
url: '/api/cases/my-case/ralph-wizard/file/research%2Fprompt.md',
});
expect(res.headers['cache-control']).toContain('no-store');
});
});
});