Files
Codeman/src/types/api.ts
T
Ark0NandClaude Opus 4.6 2ee9ad72e8 refactor: SSE event handlers, LLM context optimization, @fileoverview docs (#29)
* refactor: extract SSE event handlers into named class methods

Replace ~80 inline addListener closures in connectSSE() with a
declarative _SSE_HANDLER_MAP array that drives registration in a
single loop. Each handler is now a named _on* method on CodemanApp,
making them individually addressable for LLM navigation.

Add SSE_EVENTS constant object in constants.js to eliminate magic
event-type strings scattered across the frontend.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: fix inaccuracies in CLAUDE.md

- Fix types barrel path: src/types.ts → src/types/index.ts
- Update app.js line count: ~12K → ~11.5K
- Correct route handler counts (113 → 111, per-group fixes)
- Add code style, ESM gotcha, env vars, route test, lifecycle log docs
- Add Node 22 CI note, test teardown timeout, port range

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add mobile screenshots and QR auth security writeup to README

Add 3 mobile screenshots (landing, idle, active) and expand the
mobile section with QR auth security design details and a
touch-optimized interface subsection.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: bundle xterm-zerolag-input as vendor IIFE and add pre-commit hook

Build and postinstall now bundle the local xterm-zerolag-input package
as an IIFE at vendor/xterm-zerolag-input.js with global LocalEchoOverlay
shim. Add git pre-commit hook that runs prettier --check on staged .ts
files to catch format issues before CI.

Also bump constants.js and app.js cache-bust versions to 0.3.0 and add
tunnel upload URL display row in settings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add cloudflared install support and interactive launch menu

- Add optional cloudflared dependency detection and installation
  across 6 distro families (macOS, Debian, Fedora, Arch, Alpine, SUSE)
- Add tunnel systemd service setup helper
- Replace post-install instructions with interactive launch menu
  (run now / systemd service / skip)
- Uninstall now cleans up both codeman-web and codeman-tunnel services

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: gitignore readme-preview.mjs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: WIP — SSE event constants, @fileoverview docs, CLAUDE.md compression

- Migrate broadcast() string literals → SseEvent.* typed constants
- Add @fileoverview with cross-domain references to all 13 type domain files
- Add @fileoverview to frontend JS modules (constants, mobile, voice, etc.)
- Add section dividers to route files for LLM scanability
- Compress CLAUDE.md: flat file list → domain table, fix counts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: optimize codebase for LLM context window efficiency

CLAUDE.md: 456 → 309 lines (32% reduction)
- Merge Commands into compact table, remove redundant bash block
- Convert Security section to dense table format
- Merge Performance + Resource Limits, Debugging + Troubleshooting
- Compress Tunnel, Memory Leak, Scripts, Screenshots sections
- Remove Key Patterns that duplicate @fileoverview in source files

Backend @fileoverview enhancements (10 priority files):
- session.ts: key methods, events, cross-domain refs
- respawn-controller.ts: state machine, idle detection layers
- ralph-tracker.ts: exports, circuit breaker, events
- ralph-loop.ts: lifecycle, persistence, events
- subagent-watcher.ts: watched patterns, teammate detection
- server.ts: coordination list, port interfaces
- state-store.ts: dual-file persistence, migration
- session-manager.ts: lifecycle methods, mutex guard
- hooks-config.ts: hook events list, categories
- sse-events.ts: category breakdown (~90 events, 17 categories)

Frontend app.js: add 6 section dividers, update @fileoverview line refs

Fix: escape glob `*/` in JSDoc that broke ESLint parser

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR #29 review bugs

- server.ts: replace hardcoded 'session:needsRefresh' with SseEvent constant
- install.sh: fix Alpine cloudflared install for non-root (download to tmpfile first)
- install.sh: replace Arch pacman (AUR-only) with direct binary download
- index.html: bump all 8 remaining cache-bust versions from v0.2.9 to v0.3.0
- mobile-handlers.js: fix @dependency annotation (keyboard-accessory.js, not constants.js)
- types/push.ts: fix layer number (4, not 5)
- subagent-watcher.ts: fix watched pattern path to include {session} segment
- constants.js: fix SSE_EVENTS count in @fileoverview (~73, not ~65)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:40:18 +01:00

152 lines
4.2 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',
/** Session is currently busy */
SESSION_BUSY = 'SESSION_BUSY',
/** Operation failed */
OPERATION_FAILED = 'OPERATION_FAILED',
/** Resource already exists */
ALREADY_EXISTS = 'ALREADY_EXISTS',
/** 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.SESSION_BUSY]: 'Session is currently busy',
[ApiErrorCode.OPERATION_FAILED]: 'The operation failed',
[ApiErrorCode.ALREADY_EXISTS]: 'Resource already exists',
[ApiErrorCode.INTERNAL_ERROR]: 'An internal error occurred',
};
/**
* 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,
};
}
/**
* Response for quick start operation
*/
export interface QuickStartResponse {
/** Whether the request succeeded */
success: boolean;
/** Created session ID */
sessionId?: string;
/** Path to case folder */
casePath?: string;
/** Case name */
caseName?: string;
/** Error message if failed */
error?: string;
}
/**
* 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
*/
export 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';
}