mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-09 16:59:43 +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:
@@ -238,7 +238,7 @@ export function registerSystemRoutes(
|
||||
|
||||
app.post('/api/tunnel/qr/regenerate', async () => {
|
||||
ctx.tunnelManager.regenerateQrToken();
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ========== Auth Session Revocation ==========
|
||||
@@ -251,7 +251,7 @@ export function registerSystemRoutes(
|
||||
// Revoke all sessions (nuclear option)
|
||||
ctx.authSessions?.clear();
|
||||
}
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -288,7 +288,7 @@ export function registerSystemRoutes(
|
||||
const child = spawn('bash', [scriptPath, url], { detached: true, stdio: 'ignore' });
|
||||
child.on('error', (err) => app.log.error({ err }, 'span-displays launch failed'));
|
||||
child.unref();
|
||||
return { success: true, url };
|
||||
return { url };
|
||||
} catch (err) {
|
||||
return reply.code(500).send(createErrorResponse(ApiErrorCode.INTERNAL_ERROR, getErrorMessage(err)));
|
||||
}
|
||||
@@ -313,7 +313,7 @@ export function registerSystemRoutes(
|
||||
app.post('/api/system/update', async (_req, reply) => {
|
||||
const result = await startUpdate();
|
||||
if (result.ok) {
|
||||
return { success: true, updateId: result.updateId, toTag: result.toTag, toVersion: result.toVersion };
|
||||
return { updateId: result.updateId, toTag: result.toTag, toVersion: result.toVersion };
|
||||
}
|
||||
const map = {
|
||||
'in-flight': { http: 409, api: ApiErrorCode.ALREADY_EXISTS },
|
||||
@@ -354,7 +354,7 @@ export function registerSystemRoutes(
|
||||
for (const s of result.cleaned) {
|
||||
lifecycleLog.log({ event: 'stale_cleaned', sessionId: s.id, name: s.name });
|
||||
}
|
||||
return { success: true, cleanedSessions: result.count };
|
||||
return { cleanedSessions: result.count };
|
||||
});
|
||||
|
||||
app.get('/api/session-lifecycle', async (req) => {
|
||||
@@ -371,7 +371,7 @@ export function registerSystemRoutes(
|
||||
since: query.since ? Number(query.since) : undefined,
|
||||
limit: query.limit ? Math.min(Number(query.limit), 1000) : 200,
|
||||
});
|
||||
return { success: true, entries };
|
||||
return { entries };
|
||||
});
|
||||
|
||||
// ========== Stats ==========
|
||||
@@ -391,7 +391,6 @@ export function registerSystemRoutes(
|
||||
app.get('/api/stats', async () => {
|
||||
const activeSessionTokens = collectActiveTokens();
|
||||
return {
|
||||
success: true,
|
||||
stats: ctx.store.getAggregateStats(activeSessionTokens),
|
||||
raw: ctx.store.getGlobalStats(),
|
||||
};
|
||||
@@ -400,7 +399,6 @@ export function registerSystemRoutes(
|
||||
app.get('/api/token-stats', async () => {
|
||||
const activeSessionTokens = collectActiveTokens();
|
||||
return {
|
||||
success: true,
|
||||
daily: ctx.store.getDailyStats(30),
|
||||
totals: ctx.store.getAggregateStats(activeSessionTokens),
|
||||
};
|
||||
@@ -413,13 +411,13 @@ export function registerSystemRoutes(
|
||||
// ========== Config ==========
|
||||
|
||||
app.get('/api/config', async () => {
|
||||
return { success: true, config: ctx.store.getConfig() };
|
||||
return { config: ctx.store.getConfig() };
|
||||
});
|
||||
|
||||
app.put('/api/config', async (req) => {
|
||||
const configData = parseBody(ConfigUpdateSchema, req.body, 'Invalid config');
|
||||
ctx.store.setConfig(configData as Partial<ReturnType<typeof ctx.store.getConfig>>);
|
||||
return { success: true, config: ctx.store.getConfig() };
|
||||
return { config: ctx.store.getConfig() };
|
||||
});
|
||||
|
||||
// ========== Debug/Memory ==========
|
||||
@@ -535,7 +533,7 @@ export function registerSystemRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
return {};
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
}
|
||||
@@ -568,7 +566,7 @@ export function registerSystemRoutes(
|
||||
}
|
||||
await fs.writeFile(SETTINGS_PATH, JSON.stringify(existingSettings, null, 2));
|
||||
|
||||
return { success: true };
|
||||
return {};
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
}
|
||||
@@ -580,7 +578,6 @@ export function registerSystemRoutes(
|
||||
const { id } = req.params as { id: string };
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
return {
|
||||
success: true,
|
||||
nice: session.niceConfig,
|
||||
};
|
||||
});
|
||||
@@ -596,7 +593,6 @@ export function registerSystemRoutes(
|
||||
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
nice: session.niceConfig,
|
||||
note: 'Nice priority only affects newly created mux sessions, not currently running ones.',
|
||||
};
|
||||
@@ -620,7 +616,7 @@ export function registerSystemRoutes(
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
await fs.writeFile(windowStatesPath, JSON.stringify(states, null, 2));
|
||||
return { success: true };
|
||||
return {};
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
}
|
||||
@@ -640,7 +636,7 @@ export function registerSystemRoutes(
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
await fs.writeFile(parentMapPath, JSON.stringify(parentMap, null, 2));
|
||||
return { success: true };
|
||||
return {};
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
}
|
||||
@@ -799,7 +795,7 @@ export function registerSystemRoutes(
|
||||
const filepath = join(SCREENSHOTS_DIR, filename);
|
||||
await fs.writeFile(filepath, filePart.data);
|
||||
|
||||
return { success: true, path: filepath, filename };
|
||||
return { path: filepath, filename };
|
||||
});
|
||||
|
||||
app.get('/api/screenshots', async () => {
|
||||
|
||||
Reference in New Issue
Block a user