mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 12:39: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:
+34
-3
@@ -25,12 +25,18 @@ export enum ApiErrorCode {
|
||||
NOT_FOUND = 'NOT_FOUND',
|
||||
/** Invalid input provided */
|
||||
INVALID_INPUT = 'INVALID_INPUT',
|
||||
/** Authentication required or failed */
|
||||
UNAUTHORIZED = 'UNAUTHORIZED',
|
||||
/** Session is currently busy */
|
||||
SESSION_BUSY = 'SESSION_BUSY',
|
||||
/** Operation failed */
|
||||
OPERATION_FAILED = 'OPERATION_FAILED',
|
||||
/** Request conflicts with current state (e.g. already running) */
|
||||
CONFLICT = 'CONFLICT',
|
||||
/** Resource already exists */
|
||||
ALREADY_EXISTS = 'ALREADY_EXISTS',
|
||||
/** Too many requests / rate limited */
|
||||
RATE_LIMITED = 'RATE_LIMITED',
|
||||
/** Operation could not be completed (well-formed but unprocessable) */
|
||||
OPERATION_FAILED = 'OPERATION_FAILED',
|
||||
/** Internal server error */
|
||||
INTERNAL_ERROR = 'INTERNAL_ERROR',
|
||||
}
|
||||
@@ -41,12 +47,37 @@ export enum ApiErrorCode {
|
||||
const ErrorMessages: Record<ApiErrorCode, string> = {
|
||||
[ApiErrorCode.NOT_FOUND]: 'The requested resource was not found',
|
||||
[ApiErrorCode.INVALID_INPUT]: 'Invalid input provided',
|
||||
[ApiErrorCode.UNAUTHORIZED]: 'Authentication required',
|
||||
[ApiErrorCode.SESSION_BUSY]: 'Session is currently busy',
|
||||
[ApiErrorCode.OPERATION_FAILED]: 'The operation failed',
|
||||
[ApiErrorCode.CONFLICT]: 'Request conflicts with the current state',
|
||||
[ApiErrorCode.ALREADY_EXISTS]: 'Resource already exists',
|
||||
[ApiErrorCode.RATE_LIMITED]: 'Too many requests',
|
||||
[ApiErrorCode.OPERATION_FAILED]: 'The operation failed',
|
||||
[ApiErrorCode.INTERNAL_ERROR]: 'An internal error occurred',
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps each API error code to its HTTP status. Single source of truth for the
|
||||
* stable HTTP contract (see docs/api-reference.md). Applied centrally so every
|
||||
* error response carries a conventional 4xx/5xx status, not 200.
|
||||
*/
|
||||
const ErrorStatus: Record<ApiErrorCode, number> = {
|
||||
[ApiErrorCode.INVALID_INPUT]: 400,
|
||||
[ApiErrorCode.UNAUTHORIZED]: 401,
|
||||
[ApiErrorCode.NOT_FOUND]: 404,
|
||||
[ApiErrorCode.SESSION_BUSY]: 409,
|
||||
[ApiErrorCode.CONFLICT]: 409,
|
||||
[ApiErrorCode.ALREADY_EXISTS]: 409,
|
||||
[ApiErrorCode.OPERATION_FAILED]: 422,
|
||||
[ApiErrorCode.RATE_LIMITED]: 429,
|
||||
[ApiErrorCode.INTERNAL_ERROR]: 500,
|
||||
};
|
||||
|
||||
/** HTTP status for an API error code (defaults to 400 for unknown codes). */
|
||||
export function httpStatusForErrorCode(code: ApiErrorCode): number {
|
||||
return ErrorStatus[code] ?? 400;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook event types triggered by Claude Code's hooks system
|
||||
*/
|
||||
|
||||
@@ -44,11 +44,20 @@ Object.assign(CodemanApp.prototype, {
|
||||
async _apiJson(path, opts = {}) {
|
||||
const res = await this._api(path, opts);
|
||||
if (!res || !res.ok) return null;
|
||||
let body;
|
||||
try {
|
||||
return await res.json();
|
||||
body = await res.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
// Uniform API envelope (stable HTTP contract): unwrap { success:true, data } → data;
|
||||
// { success:false } → null (errors also surface as a non-ok HTTP status above).
|
||||
// Legacy/bare bodies pass through unchanged.
|
||||
if (body && typeof body === 'object') {
|
||||
if (body.success === false) return null;
|
||||
if (body.success === true && 'data' in body) return body.data;
|
||||
}
|
||||
return body;
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -597,7 +597,7 @@ class CodemanApp {
|
||||
// Fetch tunnel status for header indicator (desktop only)
|
||||
this.loadTunnelStatus();
|
||||
// Share a single settings fetch between both consumers
|
||||
const settingsPromise = fetch('/api/settings').then(r => r.ok ? r.json() : null).catch(() => null);
|
||||
const settingsPromise = fetch('/api/settings').then(r => r.ok ? r.json() : null).then(env => env?.data ?? null).catch(() => null);
|
||||
this.loadQuickStartCases(null, settingsPromise);
|
||||
this._initRunMode();
|
||||
this.setupEventListeners();
|
||||
@@ -1531,13 +1531,13 @@ class CodemanApp {
|
||||
try {
|
||||
// Source 1: Transcript JSONL (best quality — clean structured text from Claude)
|
||||
const res = await fetch(`/api/sessions/${this.activeSessionId}/last-response`);
|
||||
const data = await res.json();
|
||||
const data = (await res.json())?.data ?? {};
|
||||
let lastResponse = data.text || '';
|
||||
|
||||
// Source 2: Terminal buffer fallback — strip ANSI, drop Claude CLI chrome
|
||||
if (!lastResponse) {
|
||||
const termRes = await fetch(`/api/sessions/${this.activeSessionId}/terminal`);
|
||||
const termData = await termRes.json();
|
||||
const termData = (await termRes.json())?.data ?? {};
|
||||
if (termData.terminalBuffer) {
|
||||
lastResponse = this._cleanTerminalBuffer(termData.terminalBuffer);
|
||||
}
|
||||
@@ -1567,7 +1567,7 @@ class CodemanApp {
|
||||
if (moreBtn) moreBtn.textContent = '...';
|
||||
try {
|
||||
const res = await fetch(`/api/sessions/${this.activeSessionId}/last-response?context=full`);
|
||||
const data = await res.json();
|
||||
const data = (await res.json())?.data ?? {};
|
||||
const messages = data.messages || [];
|
||||
const body = document.getElementById('responseViewerBody');
|
||||
const title = document.getElementById('responseViewerTitle');
|
||||
@@ -1618,7 +1618,7 @@ class CodemanApp {
|
||||
if (this._isLoadingBuffer) return;
|
||||
try {
|
||||
const res = await fetch(`/api/sessions/${this.activeSessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`);
|
||||
const data = await res.json();
|
||||
const data = (await res.json())?.data ?? {};
|
||||
if (data.terminalBuffer) {
|
||||
this.terminal.clear();
|
||||
this.terminal.reset();
|
||||
@@ -1648,7 +1648,7 @@ class CodemanApp {
|
||||
// Fetch buffer, clear terminal, write buffer, resize (no Ctrl+L needed)
|
||||
try {
|
||||
const res = await fetch(`/api/sessions/${data.id}/terminal`);
|
||||
const termData = await res.json();
|
||||
const termData = (await res.json())?.data ?? {};
|
||||
|
||||
this.terminal.clear();
|
||||
this.terminal.reset();
|
||||
@@ -2254,7 +2254,7 @@ class CodemanApp {
|
||||
try {
|
||||
const res = await fetch('/api/status');
|
||||
const data = await res.json();
|
||||
this.handleInit(data);
|
||||
this.handleInit(data?.data ?? {});
|
||||
} catch (err) {
|
||||
console.error('Failed to load state:', err);
|
||||
}
|
||||
@@ -2938,7 +2938,7 @@ class CodemanApp {
|
||||
_crashDiag.log('FETCH_START');
|
||||
const res = await fetch(`/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`);
|
||||
if (this._isStaleSelect(selectGen)) return;
|
||||
const data = await res.json();
|
||||
const data = (await res.json())?.data ?? {};
|
||||
_crashDiag.log(`FETCH_DONE: ${data.terminalBuffer ? (data.terminalBuffer.length/1024).toFixed(0) + 'KB' : 'empty'} truncated=${data.truncated}`);
|
||||
|
||||
if (data.terminalBuffer) {
|
||||
|
||||
@@ -149,7 +149,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
return data.path;
|
||||
return data.data.path;
|
||||
},
|
||||
|
||||
// Decode an image File through the browser and re-encode it to a format the
|
||||
|
||||
@@ -182,7 +182,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
body: JSON.stringify({ goal, config }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.ok) {
|
||||
if (data.data?.ok) {
|
||||
this.orchestratorState = { state: 'planning', plan: null };
|
||||
this.showOrchestratorPanel();
|
||||
this.renderOrchestratorPanel();
|
||||
@@ -259,8 +259,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
const res = await fetch('/api/orchestrator/status');
|
||||
const data = await res.json();
|
||||
if (data.ok) {
|
||||
this.orchestratorState = data;
|
||||
if (data.data?.ok) {
|
||||
this.orchestratorState = data.data;
|
||||
this.renderOrchestratorPanel();
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
@@ -251,7 +251,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const response = await fetch('/api/token-stats');
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.renderTokenStats(data);
|
||||
this.renderTokenStats(data.data);
|
||||
document.getElementById('tokenStatsModal').classList.add('active');
|
||||
} else {
|
||||
this.showToast('Failed to load token stats', 'error');
|
||||
@@ -2881,7 +2881,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
const res = await fetch('/api/mux-sessions');
|
||||
const data = await res.json();
|
||||
this.muxSessions = data.sessions || [];
|
||||
this.muxSessions = data.data?.sessions || [];
|
||||
this.renderMuxSessions();
|
||||
} catch (err) {
|
||||
console.error('Failed to load mux sessions:', err);
|
||||
@@ -3109,8 +3109,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
const res = await fetch('/api/mux-sessions/reconcile', { method: 'POST' });
|
||||
const data = await res.json();
|
||||
|
||||
if (data.dead && data.dead.length > 0) {
|
||||
this.showToast(`Found ${data.dead.length} dead mux session(s)`, 'warning');
|
||||
if (data.data?.dead && data.data.dead.length > 0) {
|
||||
this.showToast(`Found ${data.data.dead.length} dead mux session(s)`, 'warning');
|
||||
await this.loadMuxSessions();
|
||||
} else {
|
||||
this.showToast('All mux sessions are alive', 'success');
|
||||
@@ -3220,7 +3220,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
const res = await fetch('/api/system/stats');
|
||||
const stats = await res.json();
|
||||
this.updateSystemStatsDisplay(stats);
|
||||
this.updateSystemStatsDisplay(stats.data);
|
||||
} catch (err) {
|
||||
// Silently fail - system stats are not critical
|
||||
}
|
||||
|
||||
@@ -996,14 +996,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
return;
|
||||
}
|
||||
|
||||
const history = data.history || [];
|
||||
const history = data.data.history || [];
|
||||
if (history.length === 0) {
|
||||
this.showToast('No plan history available', 'info');
|
||||
return;
|
||||
}
|
||||
|
||||
// Show history dropdown modal
|
||||
this.showPlanHistoryModal(history, data.currentVersion);
|
||||
this.showPlanHistoryModal(history, data.data.currentVersion);
|
||||
} catch (err) {
|
||||
this.showToast('Failed to load plan history: ' + err.message, 'error');
|
||||
}
|
||||
|
||||
@@ -151,11 +151,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
const res = await fetch(`/api/cases/${encodeURIComponent(caseName)}/fix-plan`);
|
||||
const data = await res.json();
|
||||
|
||||
if (data.success && data.exists && data.todos?.length > 0) {
|
||||
if (data.success && data.data.exists && data.data.todos?.length > 0) {
|
||||
this.ralphWizardConfig.existingPlan = {
|
||||
todos: data.todos,
|
||||
stats: data.stats,
|
||||
content: data.content,
|
||||
todos: data.data.todos,
|
||||
stats: data.data.stats,
|
||||
content: data.data.content,
|
||||
};
|
||||
this.updateExistingPlanUI();
|
||||
} else {
|
||||
@@ -1054,8 +1054,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.showToast(data.error || 'Failed to start', 'error');
|
||||
return;
|
||||
}
|
||||
this.ralphClosedSessions.delete(data.sessionId);
|
||||
await this.selectSession(data.sessionId);
|
||||
this.ralphClosedSessions.delete(data.data.sessionId);
|
||||
await this.selectSession(data.data.sessionId);
|
||||
this.showToast(`Ralph Loop started in ${config.caseName}`, 'success');
|
||||
} catch (err) {
|
||||
console.error('Failed to start Ralph loop:', err);
|
||||
|
||||
@@ -1041,7 +1041,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
return;
|
||||
}
|
||||
|
||||
this.runSummaryData = data.summary;
|
||||
this.runSummaryData = data.data.summary;
|
||||
this.renderRunSummary();
|
||||
} catch (err) {
|
||||
console.error('Failed to load run summary:', err);
|
||||
|
||||
@@ -50,15 +50,15 @@ Object.assign(CodemanApp.prototype, {
|
||||
let lastUsedCase = null;
|
||||
try {
|
||||
const settings = settingsPromise ? await settingsPromise : await fetch('/api/settings').then(r => r.ok ? r.json() : null);
|
||||
if (settings) {
|
||||
lastUsedCase = settings.lastUsedCase || null;
|
||||
if (settings && settings.data) {
|
||||
lastUsedCase = settings.data.lastUsedCase || null;
|
||||
}
|
||||
} catch {
|
||||
// Ignore settings load errors
|
||||
}
|
||||
|
||||
const res = await fetch('/api/cases');
|
||||
const cases = await res.json();
|
||||
const cases = (await res.json()).data;
|
||||
this.cases = cases;
|
||||
console.log('[loadQuickStartCases] Loaded cases:', cases.map(c => c.name), 'lastUsedCase:', lastUsedCase);
|
||||
|
||||
@@ -125,7 +125,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
async updateDirDisplayForCase(caseName) {
|
||||
try {
|
||||
const res = await fetch(`/api/cases/${caseName}`);
|
||||
const data = await res.json();
|
||||
const data = (await res.json()).data;
|
||||
if (data.path) {
|
||||
document.getElementById('dirDisplay').textContent = data.path;
|
||||
document.getElementById('dirInput').value = data.path;
|
||||
@@ -304,7 +304,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
// Get case path first
|
||||
const caseRes = await fetch(`/api/cases/${caseName}`);
|
||||
let caseData = await caseRes.json();
|
||||
let caseData = (await caseRes.json()).data;
|
||||
|
||||
// Create the case if it doesn't exist
|
||||
if (!caseData.path) {
|
||||
@@ -373,7 +373,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const sessionIds = [];
|
||||
for (const result of createResults) {
|
||||
if (!result.success) throw new Error(result.error);
|
||||
sessionIds.push(result.session.id);
|
||||
sessionIds.push(result.data.session.id);
|
||||
}
|
||||
firstSessionId = sessionIds[0];
|
||||
|
||||
@@ -452,7 +452,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
// Get the case path
|
||||
const caseRes = await fetch(`/api/cases/${caseName}`);
|
||||
let caseData = await caseRes.json();
|
||||
let caseData = (await caseRes.json()).data;
|
||||
|
||||
// Create the case if it doesn't exist
|
||||
if (!caseData.path) {
|
||||
@@ -501,7 +501,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const sessionIds = [];
|
||||
for (const result of createResults) {
|
||||
if (!result.success) throw new Error(result.error);
|
||||
sessionIds.push(result.session.id);
|
||||
sessionIds.push(result.data.session.id);
|
||||
}
|
||||
|
||||
// Step 2: Start all shells in parallel
|
||||
@@ -545,7 +545,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
// Check if OpenCode is available
|
||||
const statusRes = await fetch('/api/opencode/status');
|
||||
const status = await statusRes.json();
|
||||
const status = (await statusRes.json()).data;
|
||||
if (!status.available) {
|
||||
this.terminal.writeln('\x1b[1;31m OpenCode CLI not found.\x1b[0m');
|
||||
this.terminal.writeln('\x1b[90m Install with: curl -fsSL https://opencode.ai/install | bash\x1b[0m');
|
||||
@@ -570,8 +570,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Switch to the new session (don't pre-set activeSessionId — selectSession
|
||||
// early-returns when IDs match, skipping buffer load and sendResize)
|
||||
if (data.sessionId) {
|
||||
await this.selectSession(data.sessionId);
|
||||
if (data.data.sessionId) {
|
||||
await this.selectSession(data.data.sessionId);
|
||||
}
|
||||
|
||||
this.terminal.focus();
|
||||
@@ -789,8 +789,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
const res = await fetch(`/api/sessions/${sessionId}/respawn/config`);
|
||||
const data = await res.json();
|
||||
if (data.success && data.config) {
|
||||
const c = data.config;
|
||||
if (data.success && data.data && data.data.config) {
|
||||
const c = data.data.config;
|
||||
document.getElementById('modalRespawnPrompt').value = c.updatePrompt || 'update all the docs and CLAUDE.md';
|
||||
document.getElementById('modalRespawnSendClear').checked = c.sendClear ?? true;
|
||||
document.getElementById('modalRespawnSendInit').checked = c.sendInit ?? true;
|
||||
|
||||
@@ -185,9 +185,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
// Get VAPID public key from server
|
||||
const keyData = await this._apiJson('/api/push/vapid-key');
|
||||
if (!keyData?.success) throw new Error('Failed to get VAPID key');
|
||||
if (!keyData) throw new Error('Failed to get VAPID key');
|
||||
|
||||
const applicationServerKey = urlBase64ToUint8Array(keyData.data.publicKey);
|
||||
const applicationServerKey = urlBase64ToUint8Array(keyData.publicKey);
|
||||
const subscription = await this._swRegistration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey,
|
||||
@@ -204,11 +204,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
pushPreferences: this._buildPushPreferences(),
|
||||
},
|
||||
});
|
||||
if (!data?.success) throw new Error('Failed to register subscription');
|
||||
if (!data) throw new Error('Failed to register subscription');
|
||||
|
||||
this._pushSubscription = subscription;
|
||||
this._pushSubscriptionId = data.data.id;
|
||||
localStorage.setItem('codeman-push-subscription-id', data.data.id);
|
||||
this._pushSubscriptionId = data.id;
|
||||
localStorage.setItem('codeman-push-subscription-id', data.id);
|
||||
this._updatePushUI(true);
|
||||
this.showToast('Push notifications enabled', 'success');
|
||||
} catch (err) {
|
||||
@@ -598,7 +598,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
let data = null;
|
||||
try {
|
||||
const res = await fetch('/api/system/update/status');
|
||||
if (res.ok) data = await res.json();
|
||||
if (res.ok) {
|
||||
const env = await res.json();
|
||||
data = env && env.success === true ? env.data : env;
|
||||
}
|
||||
} catch { /* server restarting — keep polling */ }
|
||||
|
||||
if (!data) {
|
||||
@@ -652,7 +655,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
async loadTunnelStatus() {
|
||||
try {
|
||||
const res = await fetch('/api/tunnel/status');
|
||||
const status = await res.json();
|
||||
const env = await res.json();
|
||||
const status = env?.success === true ? env.data : env;
|
||||
const active = status.running && status.url;
|
||||
this._tunnelUrl = active ? status.url : null;
|
||||
this._updateTunnelUrlDisplay(this._tunnelUrl);
|
||||
@@ -721,7 +725,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (!res.ok) throw new Error('Tunnel not running');
|
||||
return res.json();
|
||||
})
|
||||
.then(data => {
|
||||
.then(env => {
|
||||
const data = env?.success === true ? env.data : env;
|
||||
const container = document.getElementById('tunnelQrContainer');
|
||||
if (container && data.svg) container.innerHTML = data.svg;
|
||||
// Show auth badge, countdown, and regenerate button when auth is enabled
|
||||
@@ -754,7 +759,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Fetch URL for display
|
||||
fetch('/api/tunnel/status')
|
||||
.then(r => r.json())
|
||||
.then(status => {
|
||||
.then(env => {
|
||||
const status = env?.success === true ? env.data : env;
|
||||
const urlEl = document.getElementById('tunnelQrUrl');
|
||||
if (urlEl && status.url) {
|
||||
urlEl.textContent = status.url;
|
||||
@@ -786,7 +792,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
_refreshTunnelQrFromApi() {
|
||||
fetch('/api/tunnel/qr')
|
||||
.then(res => res.ok ? res.json() : null)
|
||||
.then(data => {
|
||||
.then(env => {
|
||||
const data = env?.success === true ? env.data : env;
|
||||
if (!data?.svg) return;
|
||||
const container = document.getElementById('tunnelQrContainer');
|
||||
if (container) container.innerHTML = data.svg;
|
||||
@@ -901,7 +908,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._tunnelPollTimer = setTimeout(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/tunnel/status');
|
||||
const status = await res.json();
|
||||
const env = await res.json();
|
||||
const status = env?.success === true ? env.data : env;
|
||||
if (status.running && status.url) {
|
||||
// Tunnel is up — update UI
|
||||
this._dismissTunnelConnecting();
|
||||
@@ -960,7 +968,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
fetch('/api/tunnel/qr')
|
||||
.then(r => { if (!r.ok) throw new Error(); return r.json(); })
|
||||
.then(data => { if (data.svg) qrInner.innerHTML = data.svg; })
|
||||
.then(env => { const data = env?.success === true ? env.data : env; if (data.svg) qrInner.innerHTML = data.svg; })
|
||||
.catch(() => { qrInner.innerHTML = '<div style="color:#999;font-size:11px;padding:20px">QR unavailable</div>'; });
|
||||
} else {
|
||||
clearTimeout(this._welcomeQrShrinkTimer);
|
||||
@@ -1032,7 +1040,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Fetch tunnel info
|
||||
try {
|
||||
const res = await fetch('/api/tunnel/info');
|
||||
const info = await res.json();
|
||||
const env = await res.json();
|
||||
const info = env?.success === true ? env.data : env;
|
||||
this._renderTunnelPanel(info);
|
||||
} catch {
|
||||
const body = document.getElementById('tunnelPanelBody');
|
||||
@@ -1166,7 +1175,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.showToast('All sessions revoked', 'success');
|
||||
// Refresh panel
|
||||
const res = await fetch('/api/tunnel/info');
|
||||
const info = await res.json();
|
||||
const env = await res.json();
|
||||
const info = env?.success === true ? env.data : env;
|
||||
this._renderTunnelPanel(info);
|
||||
} catch {
|
||||
this.showToast('Failed to revoke sessions', 'error');
|
||||
@@ -1261,7 +1271,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/session-lifecycle?${params}`);
|
||||
const data = await res.json();
|
||||
const env = await res.json();
|
||||
const data = env?.success === true ? env.data : env;
|
||||
const tbody = document.getElementById('lifecycleTableBody');
|
||||
const empty = document.getElementById('lifecycleEmpty');
|
||||
|
||||
@@ -1850,7 +1861,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
async loadAppSettingsFromServer(settingsPromise = null) {
|
||||
try {
|
||||
const settings = settingsPromise ? await settingsPromise : await fetch('/api/settings').then(r => r.ok ? r.json() : null);
|
||||
const settings = settingsPromise ? await settingsPromise : await fetch('/api/settings').then(r => r.ok ? r.json() : null).then(env => env?.success === true ? env.data : env);
|
||||
if (settings) {
|
||||
// Extract notification prefs before merging app settings
|
||||
const { notificationPreferences, voiceSettings, respawnPresets, runMode, ...appSettings } = settings;
|
||||
@@ -1942,7 +1953,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
const res = await fetch('/api/subagent-window-states');
|
||||
if (res.ok) {
|
||||
states = await res.json();
|
||||
const env = await res.json();
|
||||
states = env?.success === true ? env.data : env;
|
||||
// Also update localStorage
|
||||
localStorage.setItem('codeman-subagent-window-states', JSON.stringify(states));
|
||||
}
|
||||
@@ -2009,7 +2021,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
try {
|
||||
const res = await fetch('/api/subagent-parents');
|
||||
if (res.ok) {
|
||||
mapData = await res.json();
|
||||
const env = await res.json();
|
||||
mapData = env?.success === true ? env.data : env;
|
||||
// Update localStorage as cache
|
||||
localStorage.setItem('codeman-subagent-parents', JSON.stringify(mapData));
|
||||
}
|
||||
|
||||
@@ -868,7 +868,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
async _fetchHistorySessions() {
|
||||
const res = await fetch('/api/history/sessions');
|
||||
const data = await res.json();
|
||||
const sessions = data.sessions || [];
|
||||
const sessions = data.data?.sessions || [];
|
||||
if (sessions.length === 0) return [];
|
||||
|
||||
const byProject = new Map();
|
||||
@@ -1046,7 +1046,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Prefer already-loaded this.cases to avoid an extra request.
|
||||
const casesPromise = Array.isArray(this.cases) && this.cases.length > 0
|
||||
? Promise.resolve(this.cases)
|
||||
: fetch('/api/cases').then((r) => (r.ok ? r.json() : [])).catch(() => []);
|
||||
: fetch('/api/cases').then((r) => (r.ok ? r.json() : null)).then((d) => d?.data || []).catch(() => []);
|
||||
const [allSessions, cases] = await Promise.all([
|
||||
this._fetchHistorySessions(30),
|
||||
casesPromise,
|
||||
@@ -1173,8 +1173,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
const url = `/api/history/sessions?projectKey=${encodeURIComponent(projectKey)}&offset=${offset}&limit=${limit}`;
|
||||
const res = await fetch(url);
|
||||
const data = await res.json();
|
||||
const sessions = data.sessions || [];
|
||||
state.total = typeof data.total === 'number' ? data.total : sessions.length + offset;
|
||||
const sessions = data.data?.sessions || [];
|
||||
state.total = typeof data.data?.total === 'number' ? data.data.total : sessions.length + offset;
|
||||
|
||||
if (offset === 0 && sessions.length === 0) {
|
||||
const empty = document.createElement('div');
|
||||
@@ -1261,7 +1261,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
const createData = await createRes.json();
|
||||
if (!createData.success) throw new Error(createData.error);
|
||||
|
||||
const newSessionId = createData.session.id;
|
||||
const newSessionId = createData.data.session.id;
|
||||
|
||||
// Start interactive
|
||||
await fetch(`/api/sessions/${newSessionId}/interactive`, { method: 'POST' });
|
||||
|
||||
@@ -262,7 +262,7 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
const fixPlanPath = join(casePath, '@fix_plan.md');
|
||||
|
||||
if (!existsSync(fixPlanPath)) {
|
||||
return { success: true, exists: false, content: null, todos: [] };
|
||||
return { exists: false, content: null, todos: [] };
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -339,7 +339,6 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
|
||||
const stats = { total: todos.length, pending, inProgress, completed };
|
||||
|
||||
return {
|
||||
success: true,
|
||||
exists: true,
|
||||
content,
|
||||
todos,
|
||||
|
||||
@@ -19,6 +19,6 @@ export function registerClipboardRoutes(app: FastifyInstance, ctx: EventPort): v
|
||||
sessionId: body.sessionId ?? null,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -66,6 +66,6 @@ export function registerHookEventRoutes(
|
||||
summaryTracker.recordHookEvent(event, safeData);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort): void {
|
||||
app.delete('/api/mux-sessions/:sessionId', async (req) => {
|
||||
const { sessionId } = req.params as { sessionId: string };
|
||||
const success = await ctx.mux.killSession(sessionId);
|
||||
return { success };
|
||||
return { killed: success };
|
||||
});
|
||||
|
||||
app.post('/api/mux-sessions/reconcile', async () => {
|
||||
@@ -29,11 +29,11 @@ export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort): void {
|
||||
|
||||
app.post('/api/mux-sessions/stats/start', async () => {
|
||||
ctx.mux.startStatsCollection(STATS_COLLECTION_INTERVAL_MS);
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
app.post('/api/mux-sessions/stats/stop', async () => {
|
||||
ctx.mux.stopStatsCollection();
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ export function registerPushRoutes(app: FastifyInstance, ctx: InfraPort): void {
|
||||
if (!updated) {
|
||||
return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Subscription not found');
|
||||
}
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
app.delete('/api/push/subscribe/:id', async (req) => {
|
||||
@@ -44,6 +44,6 @@ export function registerPushRoutes(app: FastifyInstance, ctx: InfraPort): void {
|
||||
if (!removed) {
|
||||
return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Subscription not found');
|
||||
}
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ export function registerRalphRoutes(
|
||||
state: session.ralphLoopState,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// Reset circuit breaker for Ralph tracker
|
||||
@@ -110,7 +110,7 @@ export function registerRalphRoutes(
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
session.ralphTracker.resetCircuitBreaker();
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// Get Ralph status block and circuit breaker state
|
||||
|
||||
@@ -62,16 +62,16 @@ export function registerRespawnRoutes(
|
||||
const controller = ctx.respawnControllers.get(id);
|
||||
|
||||
if (controller) {
|
||||
return { success: true, config: controller.getConfig(), active: true };
|
||||
return { config: controller.getConfig(), active: true };
|
||||
}
|
||||
|
||||
// Return pre-saved config from mux-sessions.json
|
||||
const preConfig = ctx.mux.getSession(id)?.respawnConfig;
|
||||
if (preConfig) {
|
||||
return { success: true, config: preConfig, active: false };
|
||||
return { config: preConfig, active: false };
|
||||
}
|
||||
|
||||
return { success: true, config: null, active: false };
|
||||
return { config: null, active: false };
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -114,7 +114,7 @@ export function registerRespawnRoutes(
|
||||
|
||||
ctx.broadcast(SseEvent.RespawnStarted, { sessionId: id, status: controller.getStatus() });
|
||||
|
||||
return { success: true, status: controller.getStatus() };
|
||||
return { status: controller.getStatus() };
|
||||
});
|
||||
|
||||
// ========== Stop Respawn ==========
|
||||
@@ -150,7 +150,7 @@ export function registerRespawnRoutes(
|
||||
|
||||
ctx.broadcast(SseEvent.RespawnStopped, { sessionId: id });
|
||||
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ========== Update Respawn Config ==========
|
||||
@@ -169,7 +169,7 @@ export function registerRespawnRoutes(
|
||||
ctx.saveRespawnConfig(id, controller.getConfig());
|
||||
ctx.persistSessionState(session);
|
||||
ctx.broadcast(SseEvent.RespawnConfigUpdated, { sessionId: id, config: controller.getConfig() });
|
||||
return { success: true, config: controller.getConfig() };
|
||||
return { config: controller.getConfig() };
|
||||
}
|
||||
|
||||
// No controller running - save as pre-config for when respawn starts
|
||||
@@ -206,7 +206,7 @@ export function registerRespawnRoutes(
|
||||
ctx.mux.updateRespawnConfig(id, merged);
|
||||
ctx.persistSessionState(session);
|
||||
ctx.broadcast(SseEvent.RespawnConfigUpdated, { sessionId: id, config: merged });
|
||||
return { success: true, config: merged };
|
||||
return { config: merged };
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -332,7 +332,6 @@ export function registerRespawnRoutes(
|
||||
ctx.broadcast(SseEvent.RespawnStarted, { sessionId: id, status: controller.getStatus() });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Respawn enabled on existing session',
|
||||
respawnStatus: controller.getStatus(),
|
||||
};
|
||||
|
||||
@@ -15,7 +15,7 @@ export function registerScheduledRoutes(app: FastifyInstance, ctx: SessionPort &
|
||||
return Array.from(ctx.scheduledRuns.values());
|
||||
});
|
||||
|
||||
app.post('/api/scheduled', async (req): Promise<{ success: boolean; run: ScheduledRun } | ApiResponse<never>> => {
|
||||
app.post('/api/scheduled', async (req): Promise<{ run: ScheduledRun } | ApiResponse<never>> => {
|
||||
const { prompt, workingDir, durationMinutes } = parseBody(ScheduledRunSchema, req.body, 'Invalid request body');
|
||||
|
||||
// Validate workingDir exists and is a directory
|
||||
@@ -31,7 +31,7 @@ export function registerScheduledRoutes(app: FastifyInstance, ctx: SessionPort &
|
||||
}
|
||||
|
||||
const run = await ctx.startScheduledRun(prompt, workingDir || process.cwd(), durationMinutes ?? 60);
|
||||
return { success: true, run };
|
||||
return { run };
|
||||
});
|
||||
|
||||
app.delete('/api/scheduled/:id', async (req) => {
|
||||
@@ -43,7 +43,7 @@ export function registerScheduledRoutes(app: FastifyInstance, ctx: SessionPort &
|
||||
}
|
||||
|
||||
await ctx.stopScheduledRun(id);
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
app.get('/api/scheduled/:id', async (req) => {
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
createErrorResponse,
|
||||
getErrorMessage,
|
||||
type ApiResponse,
|
||||
type QuickStartResponse,
|
||||
type SessionColor,
|
||||
} from '../../types.js';
|
||||
import { Session } from '../../session.js';
|
||||
@@ -211,7 +210,7 @@ export function registerSessionRoutes(
|
||||
ctx.authSessions?.delete(sessionToken);
|
||||
}
|
||||
reply.clearCookie(AUTH_COOKIE_NAME, { path: '/' });
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -349,7 +348,7 @@ export function registerSessionRoutes(
|
||||
// Avoids serializing 2-3MB of terminal+text buffers per session creation.
|
||||
const lightState = ctx.getSessionStateWithRespawn(session);
|
||||
ctx.broadcast(SseEvent.SessionCreated, lightState);
|
||||
return { success: true, session: lightState };
|
||||
return { session: lightState };
|
||||
});
|
||||
|
||||
// ========== Rename Session ==========
|
||||
@@ -364,7 +363,7 @@ export function registerSessionRoutes(
|
||||
// Also update the mux session name if applicable
|
||||
ctx.mux.updateSessionName(id, session.name);
|
||||
persistAndBroadcastSession(ctx, session);
|
||||
return { success: true, name: session.name };
|
||||
return { name: session.name };
|
||||
});
|
||||
|
||||
// ========== Set Session Color ==========
|
||||
@@ -381,12 +380,12 @@ export function registerSessionRoutes(
|
||||
|
||||
session.setColor(body.color as SessionColor);
|
||||
persistAndBroadcastSession(ctx, session);
|
||||
return { success: true, color: session.color };
|
||||
return { color: session.color };
|
||||
});
|
||||
|
||||
// ========== Delete Session ==========
|
||||
|
||||
app.delete('/api/sessions/:id', async (req): Promise<ApiResponse> => {
|
||||
app.delete('/api/sessions/:id', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const query = req.query as { killMux?: string };
|
||||
const killMux = query.killMux !== 'false'; // Default to true
|
||||
@@ -396,7 +395,7 @@ export function registerSessionRoutes(
|
||||
}
|
||||
|
||||
await ctx.cleanupSession(id, killMux, 'user_delete');
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ========== Delete All Sessions ==========
|
||||
@@ -473,13 +472,13 @@ export function registerSessionRoutes(
|
||||
// Create a fresh tracker if one doesn't exist (shouldn't happen normally)
|
||||
const newTracker = new RunSummaryTracker(id, session.name);
|
||||
ctx.runSummaryTrackers.set(id, newTracker);
|
||||
return { success: true, summary: newTracker.getSummary() };
|
||||
return { summary: newTracker.getSummary() };
|
||||
}
|
||||
|
||||
// Update session name in case it changed
|
||||
tracker.setSessionName(session.name);
|
||||
|
||||
return { success: true, summary: tracker.getSummary() };
|
||||
return { summary: tracker.getSummary() };
|
||||
});
|
||||
|
||||
// ========== Get Active Tools ==========
|
||||
@@ -502,7 +501,7 @@ export function registerSessionRoutes(
|
||||
|
||||
// ========== Run Prompt ==========
|
||||
|
||||
app.post('/api/sessions/:id/run', async (req): Promise<ApiResponse> => {
|
||||
app.post('/api/sessions/:id/run', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const { prompt } = parseBody(RunPromptSchema, req.body);
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
@@ -517,12 +516,12 @@ export function registerSessionRoutes(
|
||||
});
|
||||
|
||||
ctx.broadcast(SseEvent.SessionRunning, { id, prompt });
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ========== Start Interactive Mode ==========
|
||||
|
||||
app.post('/api/sessions/:id/interactive', async (req): Promise<ApiResponse> => {
|
||||
app.post('/api/sessions/:id/interactive', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
@@ -554,7 +553,7 @@ export function registerSessionRoutes(
|
||||
ctx.broadcast(SseEvent.SessionInteractive, { id });
|
||||
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
|
||||
|
||||
return { success: true };
|
||||
return {};
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
}
|
||||
@@ -562,7 +561,7 @@ export function registerSessionRoutes(
|
||||
|
||||
// ========== Start Shell Mode ==========
|
||||
|
||||
app.post('/api/sessions/:id/shell', async (req): Promise<ApiResponse> => {
|
||||
app.post('/api/sessions/:id/shell', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
@@ -580,7 +579,7 @@ export function registerSessionRoutes(
|
||||
});
|
||||
ctx.broadcast(SseEvent.SessionInteractive, { id, mode: 'shell' });
|
||||
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
|
||||
return { success: true };
|
||||
return {};
|
||||
} catch (err) {
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
|
||||
}
|
||||
@@ -592,7 +591,7 @@ export function registerSessionRoutes(
|
||||
|
||||
// ========== Send Input ==========
|
||||
|
||||
app.post('/api/sessions/:id/input', async (req): Promise<ApiResponse> => {
|
||||
app.post('/api/sessions/:id/input', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const { input, useMux } = parseBody(SessionInputWithLimitSchema, req.body);
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
@@ -624,7 +623,7 @@ export function registerSessionRoutes(
|
||||
} else {
|
||||
session.write(inputStr);
|
||||
}
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ========== Send Named Key (tmux send-keys -H) ==========
|
||||
@@ -632,7 +631,7 @@ export function registerSessionRoutes(
|
||||
// Uses send-keys -H (hex) to inject 0x0a (line feed) which Claude Code's
|
||||
// Ink input recognizes as "insert newline" vs 0x0d (carriage return = submit).
|
||||
|
||||
app.post('/api/sessions/:id/send-key', async (req): Promise<ApiResponse> => {
|
||||
app.post('/api/sessions/:id/send-key', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const body = req.body as Record<string, unknown>;
|
||||
const key = typeof body?.key === 'string' ? body.key : '';
|
||||
@@ -671,18 +670,18 @@ export function registerSessionRoutes(
|
||||
console.error('[Server] send-key failed:', err);
|
||||
return createErrorResponse(ApiErrorCode.INTERNAL_ERROR, 'tmux send-keys failed');
|
||||
}
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ========== Resize Terminal ==========
|
||||
|
||||
app.post('/api/sessions/:id/resize', async (req): Promise<ApiResponse> => {
|
||||
app.post('/api/sessions/:id/resize', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const { cols, rows } = parseBody(ResizeSchema, req.body);
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
session.resize(cols, rows);
|
||||
return { success: true };
|
||||
return {};
|
||||
});
|
||||
|
||||
// ========== Get Last Response (from transcript JSONL) ==========
|
||||
@@ -1084,7 +1083,7 @@ export function registerSessionRoutes(
|
||||
const result = await session.runPrompt(prompt);
|
||||
// Clean up session after completion to prevent memory leak
|
||||
await ctx.cleanupSession(session.id, true, 'run_prompt_complete');
|
||||
return { success: true, sessionId: session.id, ...result };
|
||||
return { sessionId: session.id, ...result };
|
||||
} catch (err) {
|
||||
// Clean up session on error too
|
||||
await ctx.cleanupSession(session.id, true, 'run_prompt_error');
|
||||
@@ -1094,7 +1093,7 @@ export function registerSessionRoutes(
|
||||
|
||||
// ========== Quick Start ==========
|
||||
|
||||
app.post('/api/quick-start', async (req): Promise<QuickStartResponse> => {
|
||||
app.post('/api/quick-start', async (req) => {
|
||||
// Prevent unbounded session creation
|
||||
if (ctx.sessions.size >= MAX_CONCURRENT_SESSIONS) {
|
||||
return createErrorResponse(
|
||||
@@ -1263,7 +1262,6 @@ export function registerSessionRoutes(
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
sessionId: session.id,
|
||||
casePath,
|
||||
caseName,
|
||||
@@ -1725,6 +1723,6 @@ export function registerSessionRoutes(
|
||||
await fh.close();
|
||||
}
|
||||
|
||||
return { success: true, path: filepath, filename };
|
||||
return { path: filepath, filename };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
+37
-2
@@ -90,8 +90,21 @@ import { reconcileUpdateOnBoot } from './self-update.js';
|
||||
// Load version from package.json
|
||||
const require = createRequire(import.meta.url);
|
||||
const { version: APP_VERSION } = require('../../package.json');
|
||||
|
||||
/**
|
||||
* `/api/v1/*` is the versioned public alias of the (unversioned) `/api/*` routes.
|
||||
* Rewriting at the server level lets external clients pin to a stable surface while
|
||||
* the bundled frontend keeps using `/api/*`. See docs/api-reference.md.
|
||||
*/
|
||||
function rewriteApiV1Url(url: string): string {
|
||||
if (url === '/api/v1') return '/api';
|
||||
if (url.startsWith('/api/v1/')) return '/api/' + url.slice('/api/v1/'.length);
|
||||
return url;
|
||||
}
|
||||
import {
|
||||
getErrorMessage,
|
||||
httpStatusForErrorCode,
|
||||
ApiErrorCode,
|
||||
type PersistedRespawnConfig,
|
||||
type NiceConfig,
|
||||
type ImageDetectedEvent,
|
||||
@@ -274,11 +287,12 @@ export class WebServer extends EventEmitter {
|
||||
this.windowTitle = `codeman:${this.titleHostname}`;
|
||||
this.indexHtmlTemplate = readFileSync(join(__dirname, 'public', 'index.html'), 'utf-8');
|
||||
|
||||
const rewriteUrl = (req: { url?: string }): string => rewriteApiV1Url(req.url || '');
|
||||
if (https) {
|
||||
const { key, cert } = getOrCreateSelfSignedCert();
|
||||
this.app = Fastify({ logger: false, https: { key, cert } });
|
||||
this.app = Fastify({ logger: false, https: { key, cert }, rewriteUrl });
|
||||
} else {
|
||||
this.app = Fastify({ logger: false });
|
||||
this.app = Fastify({ logger: false, rewriteUrl });
|
||||
}
|
||||
this.mux = createMultiplexer();
|
||||
this.sse = new SseStreamManager(
|
||||
@@ -561,6 +575,27 @@ export class WebServer extends EventEmitter {
|
||||
// Cookie plugin (needed for auth session tokens)
|
||||
await this.app.register(fastifyCookie);
|
||||
|
||||
// Uniform response envelope (stable HTTP contract — docs/api-reference.md):
|
||||
// wrap bare JSON payloads as { success:true, data } and map { success:false }
|
||||
// error envelopes to a conventional HTTP status (instead of 200). Skips
|
||||
// non-JSON responses (buffers/streams) and non-/api routes.
|
||||
this.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 });
|
||||
});
|
||||
|
||||
// Anti-DNS-rebinding Host allowlist + cross-site (CSRF) Origin guard. Registered
|
||||
// before auth so forged cross-site / rebound requests are rejected up front, even
|
||||
// on the default no-password install. See docs/reports/security-review-2026-06-09.md.
|
||||
|
||||
Reference in New Issue
Block a user