mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 12:39:42 +02:00
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>
229 lines
7.4 KiB
TypeScript
229 lines
7.4 KiB
TypeScript
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
|
import { WebServer } from '../src/web/server.js';
|
|
|
|
const TEST_PORT = 3105;
|
|
|
|
describe('Scheduled Runs API', () => {
|
|
let server: WebServer;
|
|
let baseUrl: string;
|
|
const createdRuns: string[] = [];
|
|
|
|
beforeAll(async () => {
|
|
server = new WebServer(TEST_PORT, false, true);
|
|
await server.start();
|
|
baseUrl = `http://localhost:${TEST_PORT}`;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
// Cancel any remaining runs
|
|
for (const runId of createdRuns) {
|
|
try {
|
|
await fetch(`${baseUrl}/api/scheduled/${runId}`, { method: 'DELETE' });
|
|
} catch {}
|
|
}
|
|
await server.stop();
|
|
});
|
|
|
|
describe('GET /api/scheduled', () => {
|
|
it('should return empty list initially', async () => {
|
|
const response = await fetch(`${baseUrl}/api/scheduled`);
|
|
const data = await response.json();
|
|
|
|
expect(Array.isArray(data.data)).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('POST /api/scheduled', () => {
|
|
it('should create a scheduled run', async () => {
|
|
const response = await fetch(`${baseUrl}/api/scheduled`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
prompt: 'echo test',
|
|
workingDir: '/tmp',
|
|
durationMinutes: 1,
|
|
}),
|
|
});
|
|
const data = await response.json();
|
|
|
|
expect(data.success).toBe(true);
|
|
expect(data.data.run).toBeDefined();
|
|
expect(data.data.run.id).toBeDefined();
|
|
expect(data.data.run.prompt).toBe('echo test');
|
|
expect(data.data.run.durationMinutes).toBe(1);
|
|
expect(data.data.run.status).toBe('running');
|
|
|
|
createdRuns.push(data.data.run.id);
|
|
|
|
// Stop the run immediately to avoid resource usage
|
|
await fetch(`${baseUrl}/api/scheduled/${data.data.run.id}`, { method: 'DELETE' });
|
|
});
|
|
|
|
it('should set correct timestamps', async () => {
|
|
const beforeCreate = Date.now();
|
|
|
|
const response = await fetch(`${baseUrl}/api/scheduled`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
prompt: 'test timestamps',
|
|
durationMinutes: 5,
|
|
}),
|
|
});
|
|
const data = await response.json();
|
|
|
|
const afterCreate = Date.now();
|
|
|
|
expect(data.data.run.startedAt).toBeGreaterThanOrEqual(beforeCreate);
|
|
expect(data.data.run.startedAt).toBeLessThanOrEqual(afterCreate);
|
|
expect(data.data.run.endAt).toBe(data.data.run.startedAt + 5 * 60 * 1000);
|
|
|
|
createdRuns.push(data.data.run.id);
|
|
await fetch(`${baseUrl}/api/scheduled/${data.data.run.id}`, { method: 'DELETE' });
|
|
});
|
|
|
|
it('should initialize with zero completed tasks and cost', async () => {
|
|
const response = await fetch(`${baseUrl}/api/scheduled`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
prompt: 'test initial values',
|
|
durationMinutes: 1,
|
|
}),
|
|
});
|
|
const data = await response.json();
|
|
|
|
expect(data.data.run.completedTasks).toBe(0);
|
|
expect(data.data.run.totalCost).toBe(0);
|
|
// Logs may have 1 or more entries depending on timing
|
|
expect(data.data.run.logs.length).toBeGreaterThanOrEqual(1);
|
|
|
|
createdRuns.push(data.data.run.id);
|
|
await fetch(`${baseUrl}/api/scheduled/${data.data.run.id}`, { method: 'DELETE' });
|
|
});
|
|
});
|
|
|
|
describe('GET /api/scheduled/:id', () => {
|
|
it('should return scheduled run details', async () => {
|
|
// Create a run first
|
|
const createRes = await fetch(`${baseUrl}/api/scheduled`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
prompt: 'test get',
|
|
durationMinutes: 1,
|
|
}),
|
|
});
|
|
const createData = await createRes.json();
|
|
const runId = createData.data.run.id;
|
|
createdRuns.push(runId);
|
|
|
|
// Get the run
|
|
const response = await fetch(`${baseUrl}/api/scheduled/${runId}`);
|
|
const data = await response.json();
|
|
|
|
expect(data.data.id).toBe(runId);
|
|
expect(data.data.prompt).toBe('test get');
|
|
|
|
await fetch(`${baseUrl}/api/scheduled/${runId}`, { method: 'DELETE' });
|
|
});
|
|
|
|
it('should return error for non-existent run', async () => {
|
|
const response = await fetch(`${baseUrl}/api/scheduled/non-existent-id`);
|
|
const data = await response.json();
|
|
|
|
expect(data.error).toBe('Scheduled run not found');
|
|
});
|
|
});
|
|
|
|
describe('DELETE /api/scheduled/:id', () => {
|
|
it('should stop a scheduled run', async () => {
|
|
// Create a run
|
|
const createRes = await fetch(`${baseUrl}/api/scheduled`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
prompt: 'test delete',
|
|
durationMinutes: 10,
|
|
}),
|
|
});
|
|
const createData = await createRes.json();
|
|
const runId = createData.data.run.id;
|
|
|
|
// Delete/stop the run
|
|
const response = await fetch(`${baseUrl}/api/scheduled/${runId}`, {
|
|
method: 'DELETE',
|
|
});
|
|
const data = await response.json();
|
|
|
|
expect(data.success).toBe(true);
|
|
|
|
// Verify it's stopped
|
|
const getRes = await fetch(`${baseUrl}/api/scheduled/${runId}`);
|
|
const runData = await getRes.json();
|
|
expect(runData.data.status).toBe('stopped');
|
|
});
|
|
|
|
it('should return error for non-existent run', async () => {
|
|
const response = await fetch(`${baseUrl}/api/scheduled/non-existent-id`, {
|
|
method: 'DELETE',
|
|
});
|
|
const data = await response.json();
|
|
|
|
expect(data.success).toBe(false);
|
|
expect(data.error).toBe('Scheduled run not found');
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('Quick Run API', () => {
|
|
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/run', () => {
|
|
it('should create session and run prompt', async () => {
|
|
// Note: This test will actually try to run Claude
|
|
// We use a simple echo to minimize API usage
|
|
const response = await fetch(`${baseUrl}/api/run`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
prompt: 'say "test"',
|
|
workingDir: '/tmp',
|
|
}),
|
|
});
|
|
const data = await response.json();
|
|
|
|
// On success the payload is wrapped ({ success:true, data:{ sessionId, ... } });
|
|
// on failure the handler returns a bare { success:false, sessionId, error }.
|
|
expect(data.data?.sessionId ?? data.sessionId).toBeDefined();
|
|
// Note: success/failure depends on Claude actually running
|
|
});
|
|
|
|
// Skip this test - it runs real Claude CLI which is slow and flaky in CI
|
|
// The functionality is tested via the first test which uses workingDir: '/tmp'
|
|
it.skip('should use current directory when workingDir not provided', async () => {
|
|
const response = await fetch(`${baseUrl}/api/run`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
prompt: 'pwd',
|
|
}),
|
|
});
|
|
const data = await response.json();
|
|
|
|
expect(data.sessionId).toBeDefined();
|
|
}, 60000); // Increase timeout since this runs real Claude CLI
|
|
});
|
|
});
|