mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-03 05:59:43 +02:00
A 15-agent audit of the merged tree confirmed 9 envelope/contract bugs;
all fixed here, with live-server contract tests added:
Blockers (fresh-install quick start broken):
- session-ui.js runClaude/runShell unwrapped .data from the /api/cases/:name
404 error envelope (which has no data key), so a not-yet-created case threw
TypeError instead of triggering the auto-create fallback. Now '?.data ?? {}'.
Contract violations on the new stable surface:
- Unknown /api routes returned HTTP 404 with {success:true,...} (Fastify's
default not-found payload was wrapped by the envelope hook). Added a
setNotFoundHandler returning the standard error envelope for /api paths.
- POST /api/events/subscribe 400 body became {success:true,data:{error}};
now createErrorResponse(INVALID_INPUT).
- POST /api/clipboard validation error lacked errorCode and shipped HTTP 200;
now createErrorResponse(INVALID_INPUT) -> 400.
- POST /api/run catch path returned bare {success:false,sessionId,error}
(HTTP 200, no errorCode); now OPERATION_FAILED envelope -> 422 with the
dead session id in the message.
- DELETE tail-file/:streamId returned {success: closed}, colliding with the
envelope discriminator; now returns {closed}.
Dead/regressed UI paths:
- Plan history modal could never open: route returned the bare history array
under data while the frontend read data.data.history/currentVersion. Route
now returns {history, currentVersion}; modal task count fixed to stats.total.
- Self-update error toast read j.error.message from the string-typed envelope
error, always falling back to the generic message; now reads the string.
Cleanup:
- Removed the stale QuickStartResponse type (unreferenced; documented the
pre-envelope shape and invited success-key collisions).
Tests: new test/http-contract.test.ts boots a real WebServer (port 3168) and
pins the envelope, /api/v1 alias, error statuses, and the /api 404 shape —
the route-test harness does not install the server-level hook, so these need
the live server. Updated file-routes/plan-routes/scheduled-runs tests to the
fixed shapes.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
167 lines
5.1 KiB
TypeScript
167 lines
5.1 KiB
TypeScript
/**
|
|
* @fileoverview API types and error handling.
|
|
*
|
|
* Defines the standardized API response envelope (ApiResponse), error codes,
|
|
* hook event types from Claude Code's hooks system, and utility functions
|
|
* for error message extraction. Used by all route modules in `src/web/routes/`.
|
|
*
|
|
* Key exports:
|
|
* - ApiResponse<T> — discriminated union envelope (success with data or error with code)
|
|
* - ApiErrorCode — enum of standard error codes with user-friendly messages
|
|
* - HookEventType — union of Claude Code hook event names (idle_prompt, stop, etc.)
|
|
* - createErrorResponse() — factory for consistent error responses
|
|
* - getErrorMessage() — safe extraction from unknown catch values
|
|
* - CaseInfo, QuickStartResponse — case folder metadata types
|
|
*
|
|
* No dependencies on other domain modules. Consumed by all route modules
|
|
* and validated via Zod schemas in `src/web/schemas.ts`.
|
|
*/
|
|
|
|
/**
|
|
* Standard error codes for API responses
|
|
*/
|
|
export enum ApiErrorCode {
|
|
/** Resource not found */
|
|
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',
|
|
/** 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',
|
|
}
|
|
|
|
/**
|
|
* User-friendly error messages for each error code
|
|
*/
|
|
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.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
|
|
*/
|
|
export type HookEventType =
|
|
| 'idle_prompt'
|
|
| 'permission_prompt'
|
|
| 'elicitation_dialog'
|
|
| 'stop'
|
|
| 'teammate_idle'
|
|
| 'task_completed';
|
|
|
|
// ========== API Response Types ==========
|
|
|
|
/**
|
|
* Standard API response wrapper (discriminated union for type safety)
|
|
* @template T Type of the data payload
|
|
*/
|
|
export type ApiResponse<T = unknown> =
|
|
| { success: true; data?: T }
|
|
| { success: false; error: string; errorCode: ApiErrorCode };
|
|
|
|
/**
|
|
* Creates a standardized error response
|
|
* @param code Error code
|
|
* @param details Optional detailed error message
|
|
* @returns Formatted error response
|
|
*/
|
|
export function createErrorResponse(code: ApiErrorCode, details?: string): ApiResponse<never> {
|
|
return {
|
|
success: false,
|
|
error: details || ErrorMessages[code],
|
|
errorCode: code,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Information about a case folder
|
|
*/
|
|
export interface CaseInfo {
|
|
/** Case name */
|
|
name: string;
|
|
/** Full path to case folder */
|
|
path: string;
|
|
/** Whether CLAUDE.md exists */
|
|
hasClaudeMd?: boolean;
|
|
}
|
|
|
|
// ========== Error Handling Utilities ==========
|
|
|
|
/**
|
|
* Type guard to check if a value is an Error instance
|
|
* @param value The value to check
|
|
* @returns True if the value is an Error instance
|
|
*/
|
|
function isError(value: unknown): value is Error {
|
|
return value instanceof Error;
|
|
}
|
|
|
|
/**
|
|
* Safely extracts an error message from an unknown caught value.
|
|
* Handles the TypeScript 4.4+ unknown error type in catch blocks.
|
|
*
|
|
* @param error The caught error (type unknown in strict mode)
|
|
* @returns A string error message
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* try {
|
|
* await riskyOperation();
|
|
* } catch (err) {
|
|
* console.error('Failed:', getErrorMessage(err));
|
|
* }
|
|
* ```
|
|
*/
|
|
export function getErrorMessage(error: unknown): string {
|
|
if (isError(error)) {
|
|
return error.message;
|
|
}
|
|
if (typeof error === 'string') {
|
|
return error;
|
|
}
|
|
if (error && typeof error === 'object' && 'message' in error) {
|
|
return String((error as { message: unknown }).message);
|
|
}
|
|
return 'An unknown error occurred';
|
|
}
|