Files
Codeman/test/routes/scheduled-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

266 lines
7.8 KiB
TypeScript

/**
* @fileoverview Tests for scheduled-routes route handlers.
*
* Uses app.inject() — no real HTTP ports needed.
* Port: N/A (app.inject doesn't open ports)
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerScheduledRoutes } from '../../src/web/routes/scheduled-routes.js';
describe('scheduled-routes', () => {
let harness: RouteTestHarness;
beforeEach(async () => {
harness = await createRouteTestHarness(registerScheduledRoutes);
});
afterEach(async () => {
await harness.app.close();
});
// ========== GET /api/scheduled ==========
describe('GET /api/scheduled', () => {
it('returns empty array when no scheduled runs exist', async () => {
const res = await harness.app.inject({
method: 'GET',
url: '/api/scheduled',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body).toEqual([]);
});
it('returns all scheduled runs', async () => {
const run1 = {
id: 'run-1',
prompt: 'test prompt 1',
workingDir: '/tmp/test',
durationMinutes: 60,
startedAt: Date.now(),
endAt: Date.now() + 3600000,
status: 'running' as const,
sessionId: null,
completedTasks: 0,
totalCost: 0,
logs: [],
};
const run2 = {
id: 'run-2',
prompt: 'test prompt 2',
workingDir: '/tmp/test2',
durationMinutes: 120,
startedAt: Date.now(),
endAt: Date.now() + 7200000,
status: 'completed' as const,
sessionId: 'sess-1',
completedTasks: 5,
totalCost: 1.5,
logs: ['started'],
};
harness.ctx.scheduledRuns.set('run-1', run1);
harness.ctx.scheduledRuns.set('run-2', run2);
const res = await harness.app.inject({
method: 'GET',
url: '/api/scheduled',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body).toHaveLength(2);
});
});
// ========== POST /api/scheduled ==========
describe('POST /api/scheduled', () => {
it('creates a scheduled run with valid input', async () => {
const mockRun = {
id: 'new-run',
prompt: 'do something',
workingDir: '/tmp',
durationMinutes: 60,
startedAt: Date.now(),
endAt: Date.now() + 3600000,
status: 'running' as const,
sessionId: null,
completedTasks: 0,
totalCost: 0,
logs: [],
};
harness.ctx.startScheduledRun = vi.fn(async () => mockRun);
const res = await harness.app.inject({
method: 'POST',
url: '/api/scheduled',
payload: {
prompt: 'do something',
durationMinutes: 60,
},
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
// Handler returns a bare { run } now; the uniform envelope wraps it to
// { success:true, data:{ run } } in production. At the route-handler layer
// the harness sees the bare return, so assert body.run directly.
expect(body.run.id).toBe('new-run');
});
it('rejects empty prompt', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/scheduled',
payload: {
prompt: '',
},
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('rejects missing prompt', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/scheduled',
payload: {},
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('rejects invalid workingDir with shell metacharacters', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/scheduled',
payload: {
prompt: 'test prompt',
workingDir: '/tmp/test;rm -rf /',
},
});
expect(res.statusCode).toBe(400);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
});
it('accepts optional durationMinutes', async () => {
const mockRun = {
id: 'run-default-duration',
prompt: 'test',
workingDir: process.cwd(),
durationMinutes: 60,
startedAt: Date.now(),
endAt: Date.now() + 3600000,
status: 'running' as const,
sessionId: null,
completedTasks: 0,
totalCost: 0,
logs: [],
};
harness.ctx.startScheduledRun = vi.fn(async () => mockRun);
const res = await harness.app.inject({
method: 'POST',
url: '/api/scheduled',
payload: {
prompt: 'test',
},
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
// Bare { run } return (envelope-wrapped to { success:true, data:{ run } }
// in production; harness sees the bare return).
expect(body.run).toBeDefined();
// Should default to 60 minutes
expect(harness.ctx.startScheduledRun).toHaveBeenCalledWith('test', expect.any(String), 60);
});
});
// ========== DELETE /api/scheduled/:id ==========
describe('DELETE /api/scheduled/:id', () => {
it('deletes an existing scheduled run', async () => {
const run = {
id: 'run-to-delete',
prompt: 'test',
workingDir: '/tmp',
durationMinutes: 60,
startedAt: Date.now(),
endAt: Date.now() + 3600000,
status: 'running' as const,
sessionId: null,
completedTasks: 0,
totalCost: 0,
logs: [],
};
harness.ctx.scheduledRuns.set('run-to-delete', run);
const res = await harness.app.inject({
method: 'DELETE',
url: '/api/scheduled/run-to-delete',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
// Handler returns a bare {} on success; the uniform envelope wraps it to
// { success:true, data:{} } in production. The harness sees the bare return.
expect(body).toEqual({});
expect(harness.ctx.stopScheduledRun).toHaveBeenCalledWith('run-to-delete');
});
it('returns error for nonexistent scheduled run', async () => {
const res = await harness.app.inject({
method: 'DELETE',
url: '/api/scheduled/nonexistent',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
expect(body.error).toBeDefined();
});
});
// ========== GET /api/scheduled/:id ==========
describe('GET /api/scheduled/:id', () => {
it('returns an existing scheduled run', async () => {
const run = {
id: 'run-1',
prompt: 'test prompt',
workingDir: '/tmp/test',
durationMinutes: 60,
startedAt: Date.now(),
endAt: Date.now() + 3600000,
status: 'running' as const,
sessionId: null,
completedTasks: 0,
totalCost: 0,
logs: [],
};
harness.ctx.scheduledRuns.set('run-1', run);
const res = await harness.app.inject({
method: 'GET',
url: '/api/scheduled/run-1',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.id).toBe('run-1');
expect(body.prompt).toBe('test prompt');
});
it('returns error for nonexistent scheduled run', async () => {
const res = await harness.app.inject({
method: 'GET',
url: '/api/scheduled/nonexistent',
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.success).toBe(false);
expect(body.error).toBeDefined();
});
});
});