mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-06 07:29:42 +02:00
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>
This commit is contained in:
@@ -3,10 +3,22 @@
|
||||
*
|
||||
* 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 { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
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
|
||||
@@ -51,11 +63,52 @@ 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: RouteTestHarness;
|
||||
let harness: CaseRouteHarness;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerCaseRoutes);
|
||||
harness = await createEnvelopeHarness();
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Default: existsSync returns false, readFile throws ENOENT
|
||||
@@ -79,7 +132,8 @@ describe('case-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body).toEqual([]);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns cases from CASES_DIR', async () => {
|
||||
@@ -97,10 +151,10 @@ describe('case-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body).toHaveLength(2);
|
||||
expect(body[0].name).toBe('my-case');
|
||||
expect(body[1].name).toBe('other-case');
|
||||
expect(body[0].hasClaudeMd).toBe(false);
|
||||
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 () => {
|
||||
@@ -113,7 +167,7 @@ describe('case-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body[0].hasClaudeMd).toBe(true);
|
||||
expect(body.data[0].hasClaudeMd).toBe(true);
|
||||
});
|
||||
|
||||
it('includes linked cases from linked-cases.json', async () => {
|
||||
@@ -141,7 +195,7 @@ describe('case-routes', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
// Should have both regular and linked cases
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
expect(body.data.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -189,7 +243,7 @@ describe('case-routes', () => {
|
||||
url: '/api/cases',
|
||||
payload: { name: 'existing-case' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(409);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('already exists');
|
||||
@@ -250,7 +304,7 @@ describe('case-routes', () => {
|
||||
url: '/api/cases/link',
|
||||
payload: { name: 'my-project', path: '/nonexistent/path' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(404);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('not found');
|
||||
@@ -265,7 +319,7 @@ describe('case-routes', () => {
|
||||
url: '/api/cases/link',
|
||||
payload: { name: 'existing-case', path: '/home/user/project' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(409);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('already exists');
|
||||
@@ -310,8 +364,9 @@ describe('case-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.name).toBe('my-case');
|
||||
expect(body.linked).toBe(true);
|
||||
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 () => {
|
||||
@@ -326,7 +381,8 @@ describe('case-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.name).toBe('regular-case');
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.name).toBe('regular-case');
|
||||
});
|
||||
|
||||
it('returns error when case not found anywhere', async () => {
|
||||
@@ -337,7 +393,7 @@ describe('case-routes', () => {
|
||||
method: 'GET',
|
||||
url: '/api/cases/nonexistent',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(404);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('not found');
|
||||
@@ -358,9 +414,9 @@ describe('case-routes', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.exists).toBe(false);
|
||||
expect(body.content).toBeNull();
|
||||
expect(body.todos).toEqual([]);
|
||||
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 () => {
|
||||
@@ -397,9 +453,9 @@ describe('case-routes', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.exists).toBe(true);
|
||||
expect(body.todos.length).toBeGreaterThan(0);
|
||||
expect(body.stats.total).toBeGreaterThan(0);
|
||||
expect(body.data.exists).toBe(true);
|
||||
expect(body.data.todos.length).toBeGreaterThan(0);
|
||||
expect(body.data.stats.total).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -413,7 +469,7 @@ describe('case-routes', () => {
|
||||
method: 'GET',
|
||||
url: '/api/cases/my-case/ralph-wizard/files',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(404);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('not found');
|
||||
@@ -424,7 +480,7 @@ describe('case-routes', () => {
|
||||
method: 'GET',
|
||||
url: '/api/cases/..%2F..%2Fetc/ralph-wizard/files',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
@@ -464,7 +520,7 @@ describe('case-routes', () => {
|
||||
method: 'GET',
|
||||
url: '/api/cases/my-case/ralph-wizard/file/research%2Fprompt.md',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(404);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
|
||||
@@ -3,17 +3,73 @@
|
||||
*
|
||||
* Uses app.inject() — no real HTTP ports needed.
|
||||
* Port: N/A (app.inject doesn't open ports)
|
||||
*
|
||||
* These tests assert the UNIFORM response envelope (stable HTTP contract):
|
||||
* success -> 2xx, { success: true, data: <payload> }
|
||||
* error -> 4xx/5xx, { success: false, error, errorCode }
|
||||
* The production server applies this via a preSerialization hook (server.ts).
|
||||
* The shared route harness doesn't install it, so we build a local harness here
|
||||
* that mirrors production: the same preSerialization envelope hook + the shared
|
||||
* route error handler, so assertions match the real wire format.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
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 { registerHookEventRoutes } from '../../src/web/routes/hook-event-routes.js';
|
||||
|
||||
interface LocalHarness {
|
||||
app: FastifyInstance;
|
||||
ctx: MockRouteContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a Fastify instance that mirrors production's uniform-envelope behavior
|
||||
* (server.ts preSerialization hook) so the test wire format matches the contract:
|
||||
* bare payloads become { success: true, data }, and { success:false } error
|
||||
* envelopes get the conventional HTTP status from their errorCode.
|
||||
*/
|
||||
async function createEnvelopeHarness(
|
||||
registerFn: (app: FastifyInstance, ctx: MockRouteContext) => void
|
||||
): Promise<LocalHarness> {
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
|
||||
const ctx = createMockRouteContext();
|
||||
registerFn(app, ctx);
|
||||
|
||||
// Mirror production uniform response envelope (server.ts).
|
||||
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 });
|
||||
});
|
||||
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
|
||||
return { app, ctx };
|
||||
}
|
||||
|
||||
describe('hook-event-routes', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let harness: LocalHarness;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerHookEventRoutes);
|
||||
harness = await createEnvelopeHarness(registerHookEventRoutes);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -69,7 +125,7 @@ describe('hook-event-routes', () => {
|
||||
data: null,
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(404);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toBeDefined();
|
||||
|
||||
@@ -15,9 +15,7 @@ describe('mux-routes', () => {
|
||||
beforeEach(async () => {
|
||||
// Add mux methods that mux-routes needs but mock-route-context doesn't provide
|
||||
harness = await createRouteTestHarness(registerMuxRoutes);
|
||||
harness.ctx.mux.getSessionsWithStats = vi.fn(async () => [
|
||||
{ name: 'codeman-abc', pid: 1234, created: Date.now() },
|
||||
]);
|
||||
harness.ctx.mux.getSessionsWithStats = vi.fn(async () => [{ name: 'codeman-abc', pid: 1234, created: Date.now() }]);
|
||||
harness.ctx.mux.isAvailable = vi.fn(() => true);
|
||||
harness.ctx.mux.reconcileSessions = vi.fn(async () => ({
|
||||
orphaned: [],
|
||||
@@ -74,7 +72,7 @@ describe('mux-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.killed).toBe(true);
|
||||
expect(harness.ctx.mux.killSession).toHaveBeenCalledWith('codeman-abc');
|
||||
});
|
||||
|
||||
@@ -87,7 +85,7 @@ describe('mux-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.killed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -119,7 +117,7 @@ describe('mux-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body).toEqual({});
|
||||
expect(harness.ctx.mux.startStatsCollection).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -134,7 +132,7 @@ describe('mux-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body).toEqual({});
|
||||
expect(harness.ctx.mux.stopStatsCollection).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -131,7 +131,11 @@ describe('push-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// Handler returns a bare {} on success; the uniform envelope wraps it to
|
||||
// { success:true, data:{} } in production. At the route-handler layer the
|
||||
// harness sees the bare return, so the meaningful check is the empty body
|
||||
// plus the pushStore call below.
|
||||
expect(body).toEqual({});
|
||||
expect(harness.ctx.pushStore.updatePreferences).toHaveBeenCalledWith('sub-123', {
|
||||
'session:idle': true,
|
||||
'session:error': true,
|
||||
@@ -176,7 +180,11 @@ describe('push-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// Handler returns a bare {} on success; the uniform envelope wraps it to
|
||||
// { success:true, data:{} } in production. At the route-handler layer the
|
||||
// harness sees the bare return, so the meaningful check is the empty body
|
||||
// plus the pushStore call below.
|
||||
expect(body).toEqual({});
|
||||
expect(harness.ctx.pushStore.removeSubscription).toHaveBeenCalledWith('sub-123');
|
||||
});
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ describe('ralph-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body).toEqual({});
|
||||
});
|
||||
|
||||
it('enables ralph tracker', async () => {
|
||||
@@ -230,7 +230,7 @@ describe('ralph-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body).toEqual({});
|
||||
expect(tracker.resetCircuitBreaker).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -69,7 +69,9 @@ describe('respawn-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// Handler now returns a bare payload; the uniform envelope wraps it to
|
||||
// { success:true, data:{ config, active } } in production. At the route-handler
|
||||
// layer the harness sees the bare return, so config/active stay top-level.
|
||||
expect(body.config).toBeNull();
|
||||
expect(body.active).toBe(false);
|
||||
});
|
||||
@@ -88,7 +90,8 @@ describe('respawn-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// Handler returns a bare { config, active } payload (wrapped under data by the
|
||||
// uniform envelope in production); the harness sees the bare return.
|
||||
expect(body.active).toBe(true);
|
||||
expect(body.config.idleTimeoutMs).toBe(5000);
|
||||
});
|
||||
@@ -121,7 +124,11 @@ describe('respawn-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// Handler returns a bare {} on success; the uniform envelope wraps it to
|
||||
// { success:true, data:{} } in production. At the route-handler layer the
|
||||
// harness sees the bare return, so success is signalled by the 200 + empty
|
||||
// body plus the side effects asserted below.
|
||||
expect(body).toEqual({});
|
||||
expect(mockController.stop).toHaveBeenCalled();
|
||||
expect(harness.ctx.respawnControllers.has(harness.ctx._sessionId)).toBe(false);
|
||||
expect(harness.ctx.broadcast).toHaveBeenCalledWith('respawn:stopped', {
|
||||
@@ -192,7 +199,9 @@ describe('respawn-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// Handler returns a bare { config } payload (wrapped under data by the uniform
|
||||
// envelope in production); the harness sees the bare return.
|
||||
expect(body.config).toBeDefined();
|
||||
expect(mockController.updateConfig).toHaveBeenCalled();
|
||||
expect(harness.ctx.broadcast).toHaveBeenCalledWith(
|
||||
'respawn:configUpdated',
|
||||
@@ -208,7 +217,9 @@ describe('respawn-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// Handler returns a bare { config } payload (wrapped under data by the uniform
|
||||
// envelope in production); the harness sees the bare return.
|
||||
expect(body.config).toBeDefined();
|
||||
expect(harness.ctx.mux.updateRespawnConfig).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -102,7 +102,9 @@ describe('scheduled-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// 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');
|
||||
});
|
||||
|
||||
@@ -169,7 +171,9 @@ describe('scheduled-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// 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);
|
||||
});
|
||||
@@ -200,7 +204,9 @@ describe('scheduled-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
// 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');
|
||||
});
|
||||
|
||||
|
||||
@@ -3,10 +3,22 @@
|
||||
*
|
||||
* Uses app.inject() (Fastify's built-in test helper) — no real HTTP ports needed.
|
||||
* Port: N/A (app.inject doesn't open ports)
|
||||
*
|
||||
* These tests assert the UNIFORM response envelope (stable HTTP contract):
|
||||
* success -> 2xx, { success: true, data: <payload> }
|
||||
* error -> 4xx/5xx, { success: false, error, errorCode }
|
||||
* The production server applies this via a preSerialization hook (server.ts).
|
||||
* The shared route harness doesn't install it, so we build a local harness here
|
||||
* that mirrors production: the same preSerialization envelope hook + the shared
|
||||
* route error handler, so assertions match the real wire format.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
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';
|
||||
|
||||
// Mock execFile so the send-key route's `tmux` invocation is observable (not run for real).
|
||||
const { execFile } = vi.hoisted(() => ({ execFile: vi.fn() }));
|
||||
@@ -17,11 +29,55 @@ vi.mock('node:child_process', async (orig) => {
|
||||
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
|
||||
interface LocalHarness {
|
||||
app: FastifyInstance;
|
||||
ctx: MockRouteContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a Fastify instance that mirrors production's uniform-envelope behavior
|
||||
* (server.ts preSerialization hook) so the test wire format matches the contract:
|
||||
* bare payloads become { success: true, data }, and { success:false } error
|
||||
* envelopes get the conventional HTTP status from their errorCode.
|
||||
*/
|
||||
async function createEnvelopeHarness(
|
||||
registerFn: (app: FastifyInstance, ctx: MockRouteContext) => void
|
||||
): Promise<LocalHarness> {
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
|
||||
const ctx = createMockRouteContext();
|
||||
registerFn(app, ctx);
|
||||
|
||||
// Mirror production uniform response envelope (server.ts).
|
||||
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 });
|
||||
});
|
||||
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
|
||||
return { app, ctx };
|
||||
}
|
||||
|
||||
describe('session-routes', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let harness: LocalHarness;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerSessionRoutes);
|
||||
harness = await createEnvelopeHarness(registerSessionRoutes);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -73,15 +129,15 @@ describe('session-routes', () => {
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/sessions' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body).toHaveLength(1);
|
||||
expect(Array.isArray(body.data)).toBe(true);
|
||||
expect(body.data).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('returns empty array when no sessions', async () => {
|
||||
harness.ctx.sessions.clear();
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/sessions' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body)).toEqual([]);
|
||||
expect(JSON.parse(res.body).data).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -95,7 +151,7 @@ describe('session-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.id).toBe(harness.ctx._sessionId);
|
||||
expect(body.data.id).toBe(harness.ctx._sessionId);
|
||||
});
|
||||
|
||||
it('returns error for unknown session', async () => {
|
||||
@@ -129,7 +185,7 @@ describe('session-routes', () => {
|
||||
method: 'DELETE',
|
||||
url: '/api/sessions/nonexistent',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(404);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
@@ -163,7 +219,7 @@ describe('session-routes', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.name).toBe('new-name');
|
||||
expect(body.data.name).toBe('new-name');
|
||||
expect(harness.ctx.persistSessionState).toHaveBeenCalled();
|
||||
expect(harness.ctx.broadcast).toHaveBeenCalledWith('session:updated', expect.anything());
|
||||
});
|
||||
@@ -192,7 +248,7 @@ describe('session-routes', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.color).toBe('blue');
|
||||
expect(body.data.color).toBe('blue');
|
||||
});
|
||||
|
||||
it('rejects invalid color', async () => {
|
||||
@@ -201,7 +257,7 @@ describe('session-routes', () => {
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/color`,
|
||||
payload: { color: 'neon-rainbow' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
@@ -304,7 +360,7 @@ describe('session-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.terminalBuffer).toBeDefined();
|
||||
expect(body.data.terminalBuffer).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns error for unknown session', async () => {
|
||||
@@ -361,7 +417,7 @@ describe('session-routes', () => {
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/run`,
|
||||
payload: { prompt: 'test' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(409);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
@@ -397,7 +453,7 @@ describe('session-routes', () => {
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/interactive`,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(409);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
@@ -423,7 +479,7 @@ describe('session-routes', () => {
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/shell`,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.statusCode).toBe(409);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
@@ -512,8 +568,8 @@ describe('session-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body).toHaveProperty('sessions');
|
||||
expect(Array.isArray(body.sessions)).toBe(true);
|
||||
expect(body.data).toHaveProperty('sessions');
|
||||
expect(Array.isArray(body.data.sessions)).toBe(true);
|
||||
});
|
||||
|
||||
it('sessions have required fields', async () => {
|
||||
@@ -522,7 +578,7 @@ describe('session-routes', () => {
|
||||
url: '/api/history/sessions',
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
for (const session of body.sessions) {
|
||||
for (const session of body.data.sessions) {
|
||||
expect(session).toHaveProperty('sessionId');
|
||||
expect(session).toHaveProperty('workingDir');
|
||||
expect(session).toHaveProperty('projectKey');
|
||||
@@ -539,7 +595,7 @@ describe('session-routes', () => {
|
||||
url: '/api/history/sessions',
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
const dates = body.sessions.map((s: { lastModified: string }) => new Date(s.lastModified).getTime());
|
||||
const dates = body.data.sessions.map((s: { lastModified: string }) => new Date(s.lastModified).getTime());
|
||||
for (let i = 1; i < dates.length; i++) {
|
||||
expect(dates[i - 1]).toBeGreaterThanOrEqual(dates[i]);
|
||||
}
|
||||
@@ -551,7 +607,7 @@ describe('session-routes', () => {
|
||||
url: '/api/history/sessions',
|
||||
});
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.sessions.length).toBeLessThanOrEqual(50);
|
||||
expect(body.data.sessions.length).toBeLessThanOrEqual(50);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -572,7 +628,7 @@ describe('session-routes', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.session).toBeDefined();
|
||||
expect(body.data.session).toBeDefined();
|
||||
});
|
||||
|
||||
it('rejects invalid resumeSessionId format', async () => {
|
||||
|
||||
@@ -140,7 +140,6 @@ describe('system-routes', () => {
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/config' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.config).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -156,7 +155,7 @@ describe('system-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.config).toBeDefined();
|
||||
expect(harness.ctx.store.setConfig).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -179,7 +178,6 @@ describe('system-routes', () => {
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/stats' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.stats).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -191,7 +189,6 @@ describe('system-routes', () => {
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/token-stats' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.daily).toBeDefined();
|
||||
expect(body.totals).toBeDefined();
|
||||
});
|
||||
@@ -230,7 +227,6 @@ describe('system-routes', () => {
|
||||
const res = await harness.app.inject({ method: 'POST', url: '/api/cleanup-state' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.cleanedSessions).toBe(0);
|
||||
expect(harness.ctx.store.cleanupStaleSessions).toHaveBeenCalled();
|
||||
});
|
||||
@@ -266,7 +262,7 @@ describe('system-routes', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body).toEqual({});
|
||||
});
|
||||
|
||||
it('revokes a specific session token', async () => {
|
||||
@@ -280,7 +276,6 @@ describe('system-routes', () => {
|
||||
payload: { sessionToken: 'tok-123' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(authSessions.has('tok-123')).toBe(false);
|
||||
});
|
||||
|
||||
@@ -333,8 +328,6 @@ describe('system-routes', () => {
|
||||
payload: { showSystemStats: true, subagentTrackingEnabled: false },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(mockedWriteFile).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -347,7 +340,7 @@ describe('system-routes', () => {
|
||||
payload: { showTokenCount: false },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
|
||||
// Verify writeFile was called with merged content
|
||||
const writtenContent = JSON.parse(mockedWriteFile.mock.calls[0][1] as string);
|
||||
@@ -377,7 +370,7 @@ describe('system-routes', () => {
|
||||
payload: { lastUsedCase: 'my-test-case' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
|
||||
const writtenContent = JSON.parse(mockedWriteFile.mock.calls[0][1] as string);
|
||||
expect(writtenContent.lastUsedCase).toBe('my-test-case');
|
||||
@@ -439,7 +432,7 @@ describe('system-routes', () => {
|
||||
payload: { minimized: { 'agent-1': true }, open: ['agent-2'] },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
expect(mockedWriteFile).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -450,7 +443,7 @@ describe('system-routes', () => {
|
||||
payload: { minimized: {}, open: [] },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
});
|
||||
|
||||
it('rejects invalid minimized values', async () => {
|
||||
@@ -496,7 +489,7 @@ describe('system-routes', () => {
|
||||
payload: { 'agent-1': 'session-abc' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
expect(mockedWriteFile).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -507,7 +500,7 @@ describe('system-routes', () => {
|
||||
payload: {},
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
});
|
||||
|
||||
it('rejects non-string values in parent map', async () => {
|
||||
@@ -629,7 +622,6 @@ describe('system-routes', () => {
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/session-lifecycle' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.entries).toEqual(mockEntries);
|
||||
});
|
||||
|
||||
@@ -754,7 +746,7 @@ describe('system-routes', () => {
|
||||
payload: { model: 'claude-3', temperature: 0.5 },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
expect(mockedWriteFile).toHaveBeenCalled();
|
||||
|
||||
// Verify the written content contains modelConfig
|
||||
@@ -771,7 +763,7 @@ describe('system-routes', () => {
|
||||
payload: { model: 'new-model' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
|
||||
const writtenContent = JSON.parse(mockedWriteFile.mock.calls[0][1] as string);
|
||||
expect(writtenContent.showCost).toBe(true);
|
||||
@@ -972,7 +964,7 @@ describe('system-routes', () => {
|
||||
|
||||
const res = await harness.app.inject({ method: 'POST', url: '/api/tunnel/qr/regenerate' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).success).toBe(true);
|
||||
expect(JSON.parse(res.body)).toEqual({});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -65,7 +65,10 @@ describe('POST /api/system/span-displays', () => {
|
||||
headers: { host: 'localhost:5000' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ success: true, url: 'http://localhost:5000' });
|
||||
// Handler returns a bare { url } on success; the uniform envelope wraps it to
|
||||
// { success:true, data:{ url } } in production. At the route-handler layer the
|
||||
// harness sees the bare return, so we assert on body.url directly.
|
||||
expect(res.json()).toMatchObject({ url: 'http://localhost:5000' });
|
||||
expect(spawnMock).toHaveBeenCalledTimes(1);
|
||||
const [cmd, args] = spawnMock.mock.calls[0] as [string, string[]];
|
||||
expect(cmd).toBe('bash');
|
||||
|
||||
Reference in New Issue
Block a user