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>
This commit is contained in:
Ark0N
2026-03-03 22:40:18 +01:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 14462f7bfe
commit 2ee9ad72e8
52 changed files with 3393 additions and 1860 deletions
+47 -18
View File
@@ -17,6 +17,7 @@ import {
type SessionColor,
} from '../../types.js';
import { Session } from '../../session.js';
import { SseEvent } from '../sse-events.js';
import {
CreateSessionSchema,
SessionNameSchema,
@@ -54,6 +55,10 @@ export function registerSessionRoutes(
app: FastifyInstance,
ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort
): void {
// ═══════════════════════════════════════════════════════════════
// Auth
// ═══════════════════════════════════════════════════════════════
// ========== Logout ==========
app.post('/api/logout', async (req, reply) => {
@@ -66,6 +71,10 @@ export function registerSessionRoutes(
return { success: true };
});
// ═══════════════════════════════════════════════════════════════
// Session CRUD (list, create, rename, color, delete, detail)
// ═══════════════════════════════════════════════════════════════
// ========== Session Listing ==========
app.get('/api/sessions', async () => {
@@ -146,7 +155,7 @@ export function registerSessionRoutes(
// Use light state for broadcast + response — buffers are fetched on-demand via /terminal.
// Avoids serializing 2-3MB of terminal+text buffers per session creation.
const lightState = ctx.getSessionStateWithRespawn(session);
ctx.broadcast('session:created', lightState);
ctx.broadcast(SseEvent.SessionCreated, lightState);
return { success: true, session: lightState };
});
@@ -170,7 +179,7 @@ export function registerSessionRoutes(
// Also update the mux session name if applicable
ctx.mux.updateSessionName(id, session.name);
ctx.persistSessionState(session);
ctx.broadcast('session:updated', ctx.getSessionStateWithRespawn(session));
ctx.broadcast(SseEvent.SessionUpdated, ctx.getSessionStateWithRespawn(session));
return { success: true, name: session.name };
});
@@ -196,7 +205,7 @@ export function registerSessionRoutes(
session.setColor(body.color as SessionColor);
ctx.persistSessionState(session);
ctx.broadcast('session:updated', ctx.getSessionStateWithRespawn(session));
ctx.broadcast(SseEvent.SessionUpdated, ctx.getSessionStateWithRespawn(session));
return { success: true, color: session.color };
});
@@ -246,6 +255,10 @@ export function registerSessionRoutes(
return ctx.getSessionStateWithRespawn(session);
});
// ═══════════════════════════════════════════════════════════════
// Session Data (output, ralph state, run summary, active tools)
// ═══════════════════════════════════════════════════════════════
// ========== Get Session Output ==========
app.get('/api/sessions/:id/output', async (req) => {
@@ -328,6 +341,10 @@ export function registerSessionRoutes(
};
});
// ═══════════════════════════════════════════════════════════════
// Session Execution (run prompt, interactive mode, shell mode)
// ═══════════════════════════════════════════════════════════════
// ========== Run Prompt ==========
app.post('/api/sessions/:id/run', async (req): Promise<ApiResponse> => {
@@ -349,10 +366,10 @@ export function registerSessionRoutes(
// Run async, don't wait
session.runPrompt(prompt).catch((err) => {
ctx.broadcast('session:error', { id, error: err.message });
ctx.broadcast(SseEvent.SessionError, { id, error: err.message });
});
ctx.broadcast('session:running', { id, prompt });
ctx.broadcast(SseEvent.SessionRunning, { id, prompt });
return { success: true };
});
@@ -391,8 +408,8 @@ export function registerSessionRoutes(
name: session.name,
mode: session.mode,
});
ctx.broadcast('session:interactive', { id });
ctx.broadcast('session:updated', { session: ctx.getSessionStateWithRespawn(session) });
ctx.broadcast(SseEvent.SessionInteractive, { id });
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
return { success: true };
} catch (err) {
@@ -422,14 +439,18 @@ export function registerSessionRoutes(
name: session.name,
mode: 'shell',
});
ctx.broadcast('session:interactive', { id, mode: 'shell' });
ctx.broadcast('session:updated', { session: ctx.getSessionStateWithRespawn(session) });
ctx.broadcast(SseEvent.SessionInteractive, { id, mode: 'shell' });
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
return { success: true };
} catch (err) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
}
});
// ═══════════════════════════════════════════════════════════════
// Terminal I/O (input, resize, buffer)
// ═══════════════════════════════════════════════════════════════
// ========== Send Input ==========
app.post('/api/sessions/:id/input', async (req): Promise<ApiResponse> => {
@@ -550,6 +571,10 @@ export function registerSessionRoutes(
};
});
// ═══════════════════════════════════════════════════════════════
// Session Settings (auto-clear, auto-compact, image watcher, flicker filter)
// ═══════════════════════════════════════════════════════════════
// ========== Auto-Clear ==========
app.post('/api/sessions/:id/auto-clear', async (req) => {
@@ -567,7 +592,7 @@ export function registerSessionRoutes(
session.setAutoClear(body.enabled, body.threshold);
ctx.persistSessionState(session);
ctx.broadcast('session:updated', ctx.getSessionStateWithRespawn(session));
ctx.broadcast(SseEvent.SessionUpdated, ctx.getSessionStateWithRespawn(session));
return {
success: true,
@@ -597,7 +622,7 @@ export function registerSessionRoutes(
session.setAutoCompact(body.enabled, body.threshold, body.prompt);
ctx.persistSessionState(session);
ctx.broadcast('session:updated', ctx.getSessionStateWithRespawn(session));
ctx.broadcast(SseEvent.SessionUpdated, ctx.getSessionStateWithRespawn(session));
return {
success: true,
@@ -661,7 +686,7 @@ export function registerSessionRoutes(
session.flickerFilterEnabled = body.enabled;
ctx.persistSessionState(session);
ctx.broadcast('session:updated', ctx.getSessionStateWithRespawn(session));
ctx.broadcast(SseEvent.SessionUpdated, ctx.getSessionStateWithRespawn(session));
return {
success: true,
@@ -671,6 +696,10 @@ export function registerSessionRoutes(
};
});
// ═══════════════════════════════════════════════════════════════
// Quick Actions (quick-run, quick-start)
// ═══════════════════════════════════════════════════════════════
// ========== Quick Run ==========
app.post('/api/run', async (req) => {
@@ -717,7 +746,7 @@ export function registerSessionRoutes(
reason: 'run_prompt',
});
ctx.broadcast('session:created', ctx.getSessionStateWithRespawn(session));
ctx.broadcast(SseEvent.SessionCreated, ctx.getSessionStateWithRespawn(session));
try {
const result = await session.runPrompt(prompt);
@@ -786,7 +815,7 @@ export function registerSessionRoutes(
await writeHooksConfig(casePath);
}
ctx.broadcast('case:created', { name: caseName, path: casePath });
ctx.broadcast(SseEvent.CaseCreated, { name: caseName, path: casePath });
} catch (err) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, `Failed to create case: ${getErrorMessage(err)}`);
}
@@ -831,7 +860,7 @@ export function registerSessionRoutes(
name: session.name,
reason: 'quick_start',
});
ctx.broadcast('session:created', ctx.getSessionStateWithRespawn(session));
ctx.broadcast(SseEvent.SessionCreated, ctx.getSessionStateWithRespawn(session));
// Start in the appropriate mode
try {
@@ -843,7 +872,7 @@ export function registerSessionRoutes(
name: session.name,
mode: 'shell',
});
ctx.broadcast('session:interactive', { id: session.id, mode: 'shell' });
ctx.broadcast(SseEvent.SessionInteractive, { id: session.id, mode: 'shell' });
} else {
// Both 'claude' and 'opencode' modes use startInteractive()
await session.startInteractive();
@@ -853,9 +882,9 @@ export function registerSessionRoutes(
name: session.name,
mode,
});
ctx.broadcast('session:interactive', { id: session.id, mode });
ctx.broadcast(SseEvent.SessionInteractive, { id: session.id, mode });
}
ctx.broadcast('session:updated', { session: ctx.getSessionStateWithRespawn(session) });
ctx.broadcast(SseEvent.SessionUpdated, { session: ctx.getSessionStateWithRespawn(session) });
// Save lastUsedCase to settings for TUI/web sync
try {