Files
Codeman/test/quick-start.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

318 lines
10 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import { WebServer } from '../src/web/server.js';
import { existsSync, rmSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
const TEST_PORT = 3099;
const CASES_DIR = join(homedir(), 'codeman-cases');
describe('Quick Start API', () => {
let server: WebServer;
let baseUrl: string;
const createdCases: string[] = [];
beforeAll(async () => {
server = new WebServer(TEST_PORT, false, true);
await server.start();
baseUrl = `http://localhost:${TEST_PORT}`;
});
afterEach(() => {
// Clean up cases created during this test
while (createdCases.length > 0) {
const caseName = createdCases.pop()!;
const casePath = join(CASES_DIR, caseName);
if (existsSync(casePath)) {
rmSync(casePath, { recursive: true, force: true });
}
}
});
afterAll(async () => {
await server.stop();
}, 30000);
describe('POST /api/quick-start', () => {
it('should create default testcase and start interactive session', async () => {
const testCaseName = 'test-quick-start-default-' + Date.now();
createdCases.push(testCaseName);
const response = await fetch(`${baseUrl}/api/quick-start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ caseName: testCaseName }),
});
const data = await response.json();
expect(data.success).toBe(true);
expect(data.data.sessionId).toBeDefined();
expect(data.data.caseName).toBe(testCaseName);
expect(data.data.casePath).toBe(join(CASES_DIR, testCaseName));
// Verify case folder was created
expect(existsSync(data.data.casePath)).toBe(true);
expect(existsSync(join(data.data.casePath, 'CLAUDE.md'))).toBe(true);
expect(existsSync(join(data.data.casePath, 'src'))).toBe(true);
});
it('should use existing case without recreating it', async () => {
const testCaseName = 'test-existing-case-' + Date.now();
const casePath = join(CASES_DIR, testCaseName);
createdCases.push(testCaseName);
// Pre-create the case
mkdirSync(casePath, { recursive: true });
const response = await fetch(`${baseUrl}/api/quick-start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ caseName: testCaseName }),
});
const data = await response.json();
expect(data.success).toBe(true);
expect(data.data.caseName).toBe(testCaseName);
// Case should exist but CLAUDE.md won't be created since case already exists
expect(existsSync(casePath)).toBe(true);
});
it('should reject invalid case names with special characters', async () => {
const response = await fetch(`${baseUrl}/api/quick-start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ caseName: 'invalid/case\\name!' }),
});
const data = await response.json();
expect(data.success).toBe(false);
expect(data.error).toContain('Invalid case name');
});
it('should reject case names with spaces', async () => {
const response = await fetch(`${baseUrl}/api/quick-start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ caseName: 'case with spaces' }),
});
const data = await response.json();
expect(data.success).toBe(false);
expect(data.error).toContain('Invalid case name');
});
it('should accept case names with hyphens and underscores', async () => {
const testCaseName = 'test-case_with-mixed_123-' + Date.now();
createdCases.push(testCaseName);
const response = await fetch(`${baseUrl}/api/quick-start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ caseName: testCaseName }),
});
const data = await response.json();
expect(data.success).toBe(true);
expect(data.data.caseName).toBe(testCaseName);
});
it('should default to "testcase" when no caseName provided', async () => {
// Clean up testcase if it exists from previous runs
const testcasePath = join(CASES_DIR, 'testcase');
if (!createdCases.includes('testcase')) {
createdCases.push('testcase');
}
const response = await fetch(`${baseUrl}/api/quick-start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const data = await response.json();
expect(data.success).toBe(true);
expect(data.data.caseName).toBe('testcase');
});
});
});
describe('Session Management', () => {
let server: WebServer;
let baseUrl: string;
beforeAll(async () => {
server = new WebServer(TEST_PORT + 1, false, true);
await server.start();
baseUrl = `http://localhost:${TEST_PORT + 1}`;
});
afterAll(async () => {
await server.stop();
});
describe('POST /api/sessions', () => {
it('should create a new session', async () => {
const response = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workingDir: '/tmp' }),
});
const data = await response.json();
expect(data.success).toBe(true);
expect(data.data.session).toBeDefined();
expect(data.data.session.id).toBeDefined();
expect(data.data.session.workingDir).toBe('/tmp');
expect(data.data.session.status).toBe('idle');
});
});
describe('GET /api/sessions', () => {
it('should return list of sessions', async () => {
const response = await fetch(`${baseUrl}/api/sessions`);
const data = await response.json();
expect(data.success).toBe(true);
expect(Array.isArray(data.data)).toBe(true);
});
});
describe('GET /api/status', () => {
it('should return full server state', async () => {
const response = await fetch(`${baseUrl}/api/status`);
const data = await response.json();
expect(data.success).toBe(true);
expect(data.data).toHaveProperty('sessions');
expect(data.data).toHaveProperty('scheduledRuns');
expect(data.data).toHaveProperty('respawnStatus');
expect(data.data).toHaveProperty('timestamp');
expect(Array.isArray(data.data.sessions)).toBe(true);
expect(Array.isArray(data.data.scheduledRuns)).toBe(true);
});
});
});
describe('Case Management', () => {
let server: WebServer;
let baseUrl: string;
const createdCases: string[] = [];
beforeAll(async () => {
server = new WebServer(TEST_PORT + 2, false, true);
await server.start();
baseUrl = `http://localhost:${TEST_PORT + 2}`;
});
afterAll(async () => {
await server.stop();
for (const caseName of createdCases) {
const casePath = join(CASES_DIR, caseName);
if (existsSync(casePath)) {
rmSync(casePath, { recursive: true, force: true });
}
}
});
describe('GET /api/cases', () => {
it('should return list of cases', async () => {
const response = await fetch(`${baseUrl}/api/cases`);
const data = await response.json();
expect(data.success).toBe(true);
expect(Array.isArray(data.data)).toBe(true);
});
});
describe('POST /api/cases', () => {
it('should create a new case', async () => {
const testCaseName = 'test-case-create-' + Date.now();
createdCases.push(testCaseName);
const response = await fetch(`${baseUrl}/api/cases`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: testCaseName, description: 'Test case' }),
});
const data = await response.json();
expect(data.success).toBe(true);
expect(data.data.case.name).toBe(testCaseName);
});
it('should reject duplicate case names', async () => {
const testCaseName = 'test-case-duplicate-' + Date.now();
createdCases.push(testCaseName);
// Create first case
await fetch(`${baseUrl}/api/cases`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: testCaseName }),
});
// Try to create duplicate
const response = await fetch(`${baseUrl}/api/cases`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: testCaseName }),
});
const data = await response.json();
expect(data.success).toBe(false);
expect(data.error).toContain('already exists');
});
it('should reject invalid case names', async () => {
const response = await fetch(`${baseUrl}/api/cases`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'invalid name!' }),
});
const data = await response.json();
expect(data.success).toBe(false);
expect(data.error).toContain('Invalid case name');
});
});
describe('GET /api/cases/:name', () => {
it('should return case details', async () => {
const testCaseName = 'test-case-get-' + Date.now();
createdCases.push(testCaseName);
// Create case first
await fetch(`${baseUrl}/api/cases`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: testCaseName }),
});
const response = await fetch(`${baseUrl}/api/cases/${testCaseName}`);
const data = await response.json();
expect(data.success).toBe(true);
expect(data.data.name).toBe(testCaseName);
expect(data.data.path).toBeDefined();
expect(data.data.hasClaudeMd).toBe(true);
});
it('should return error for non-existent case', async () => {
const response = await fetch(`${baseUrl}/api/cases/non-existent-case-12345`);
const data = await response.json();
expect(data.error).toBe('Case not found');
});
});
});