mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-06 07:29:42 +02:00
refactor: pass 3 — extract helpers, split long functions, deduplicate patterns
Backend: - subagent-watcher: split 176L processEntry() into 5 focused methods; extract _resolveDescription() deduplicating 3 call sites for description acquisition - bash-tool-parser: split 152L processCleanLine() into 4 handlers; extract _createActiveTool() factory and _scheduleAutoRemove() helper - session: extract _setupOrAttachMuxSession() deduplicating ~80L between startInteractive/startShell; extract _handleTerminalOutput() - respawn-controller: split 180L handleTerminalData() into 3 detection layers; data-driven validation loop replacing 9 individual calls - plan-orchestrator: extract _extractJsonFromResponse(), _emitAgentFailure(), _formatResearchSection() helpers - orchestrator-loop: extract _finalizeTask() unifying task completion/failure; _clearTimer() utility for correct clearInterval/clearTimeout dispatch - ralph-status-parser: config-driven FIELD_PARSERS[] replacing 8 near-identical field-matching blocks; split updateCircuitBreaker() into focused handlers - state-store: extract _mergeWithInitialState() and _resetCircuitBreaker() Frontend: - app.js: add _notifySession() helper used by 18 call sites across 5 modules - panels-ui.js: extract _addActivityEntry() replacing 4 duplicate blocks - settings-ui.js: extract _updateTunnelUrlRow() deduplicating 2 blocks - ralph-panel.js, respawn-ui.js: convert to _notifySession() Routes: - route-helpers: add toggleService() helper - system-routes: use toggleService() for watcher toggles; extract collectActiveTokens() - orchestrator-routes: data-driven EVENT_MAP replacing 10 identical listeners Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+16
-35
@@ -939,15 +939,7 @@ class CodemanApp {
|
||||
if (data.id === this.activeSessionId) {
|
||||
this.terminal.writeln(`\x1b[1;31m Error: ${data.error}\x1b[0m`);
|
||||
}
|
||||
const session = this.sessions.get(data.id);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'critical',
|
||||
category: 'session-error',
|
||||
sessionId: data.id,
|
||||
sessionName: session?.name || this.getShortId(data.id),
|
||||
title: 'Session Error',
|
||||
message: data.error || 'Unknown error',
|
||||
});
|
||||
this._notifySession(data.id, 'critical', 'session-error', 'Session Error', data.error || 'Unknown error');
|
||||
}
|
||||
|
||||
_onSessionExit(data) {
|
||||
@@ -960,14 +952,7 @@ class CodemanApp {
|
||||
}
|
||||
// Notify on unexpected exit (non-zero code)
|
||||
if (data.code && data.code !== 0) {
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'critical',
|
||||
category: 'session-crash',
|
||||
sessionId: data.id,
|
||||
sessionName: session?.name || this.getShortId(data.id),
|
||||
title: 'Session Crashed',
|
||||
message: `Exited with code ${data.code}`,
|
||||
});
|
||||
this._notifySession(data.id, 'critical', 'session-crash', 'Session Crashed', `Exited with code ${data.code}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -984,15 +969,7 @@ class CodemanApp {
|
||||
const threshold = this.notificationManager?.preferences?.stuckThresholdMs || 600000;
|
||||
clearTimeout(this.idleTimers.get(data.id));
|
||||
this.idleTimers.set(data.id, setTimeout(() => {
|
||||
const s = this.sessions.get(data.id);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'warning',
|
||||
category: 'session-stuck',
|
||||
sessionId: data.id,
|
||||
sessionName: s?.name || this.getShortId(data.id),
|
||||
title: 'Session Idle',
|
||||
message: `Idle for ${Math.round(threshold / 60000)}+ minutes`,
|
||||
});
|
||||
this._notifySession(data.id, 'warning', 'session-stuck', 'Session Idle', `Idle for ${Math.round(threshold / 60000)}+ minutes`);
|
||||
this.idleTimers.delete(data.id);
|
||||
}, threshold));
|
||||
}
|
||||
@@ -1023,15 +1000,7 @@ class CodemanApp {
|
||||
this.showToast(`Auto-cleared at ${data.tokens.toLocaleString()} tokens`, 'info');
|
||||
this.updateRespawnTokens(0);
|
||||
}
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'info',
|
||||
category: 'auto-clear',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || this.getShortId(data.sessionId),
|
||||
title: 'Auto-Cleared',
|
||||
message: `Context reset at ${(data.tokens || 0).toLocaleString()} tokens`,
|
||||
});
|
||||
this._notifySession(data.sessionId, 'info', 'auto-clear', 'Auto-Cleared', `Context reset at ${(data.tokens || 0).toLocaleString()} tokens`);
|
||||
}
|
||||
|
||||
_onSessionCliInfo(data) {
|
||||
@@ -1983,6 +1952,18 @@ class CodemanApp {
|
||||
return this.getShortId(session.id);
|
||||
}
|
||||
|
||||
_notifySession(sessionId, urgency, category, title, message) {
|
||||
const session = this.sessions.get(sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency,
|
||||
category,
|
||||
sessionId,
|
||||
sessionName: session?.name || this.getShortId(sessionId),
|
||||
title,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up state from the previous session before switching tabs.
|
||||
* Handles: WebSocket teardown, CJK clear, flicker filter, tab completion,
|
||||
|
||||
+13
-34
@@ -14,6 +14,13 @@
|
||||
*/
|
||||
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
_addActivityEntry(agentId, entry, maxSize = 50) {
|
||||
const activity = this.subagentActivity.get(agentId) || [];
|
||||
activity.push(entry);
|
||||
if (activity.length > maxSize) activity.shift();
|
||||
this.subagentActivity.set(agentId, activity);
|
||||
},
|
||||
|
||||
// Tasks
|
||||
_onTaskCreated(data) {
|
||||
this.renderSessionTabs();
|
||||
@@ -106,15 +113,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Notify about new subagent discovery
|
||||
const parentId = this.subagentParentMap.get(data.agentId);
|
||||
const parentSession = parentId ? this.sessions.get(parentId) : null;
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'info',
|
||||
category: 'subagent-spawn',
|
||||
sessionId: parentId || data.sessionId,
|
||||
sessionName: parentSession?.name || parentId || data.sessionId,
|
||||
title: 'Subagent Spawned',
|
||||
message: data.description || 'New background agent started',
|
||||
});
|
||||
this._notifySession(parentId || data.sessionId, 'info', 'subagent-spawn', 'Subagent Spawned', data.description || 'New background agent started');
|
||||
},
|
||||
|
||||
_onSubagentUpdated(data) {
|
||||
@@ -135,10 +134,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
_onSubagentToolCall(data) {
|
||||
const activity = this.subagentActivity.get(data.agentId) || [];
|
||||
activity.push({ type: 'tool', ...data });
|
||||
if (activity.length > 50) activity.shift(); // Keep last 50 entries
|
||||
this.subagentActivity.set(data.agentId, activity);
|
||||
this._addActivityEntry(data.agentId, { type: 'tool', ...data });
|
||||
if (this.activeSubagentId === data.agentId) {
|
||||
this.renderSubagentDetail();
|
||||
}
|
||||
@@ -150,10 +146,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
_onSubagentProgress(data) {
|
||||
const activity = this.subagentActivity.get(data.agentId) || [];
|
||||
activity.push({ type: 'progress', ...data });
|
||||
if (activity.length > 50) activity.shift();
|
||||
this.subagentActivity.set(data.agentId, activity);
|
||||
this._addActivityEntry(data.agentId, { type: 'progress', ...data });
|
||||
if (this.activeSubagentId === data.agentId) {
|
||||
this.renderSubagentDetail();
|
||||
}
|
||||
@@ -164,10 +157,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
_onSubagentMessage(data) {
|
||||
const activity = this.subagentActivity.get(data.agentId) || [];
|
||||
activity.push({ type: 'message', ...data });
|
||||
if (activity.length > 50) activity.shift();
|
||||
this.subagentActivity.set(data.agentId, activity);
|
||||
this._addActivityEntry(data.agentId, { type: 'message', ...data });
|
||||
if (this.activeSubagentId === data.agentId) {
|
||||
this.renderSubagentDetail();
|
||||
}
|
||||
@@ -190,10 +180,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
|
||||
// Add to activity stream
|
||||
const activity = this.subagentActivity.get(data.agentId) || [];
|
||||
activity.push({ type: 'tool_result', ...data });
|
||||
if (activity.length > 50) activity.shift();
|
||||
this.subagentActivity.set(data.agentId, activity);
|
||||
this._addActivityEntry(data.agentId, { type: 'tool_result', ...data });
|
||||
|
||||
if (this.activeSubagentId === data.agentId) {
|
||||
this.renderSubagentDetail();
|
||||
@@ -224,15 +211,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Notify about subagent completion
|
||||
const parentId = this.subagentParentMap.get(data.agentId);
|
||||
const parentSession = parentId ? this.sessions.get(parentId) : null;
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'info',
|
||||
category: 'subagent-complete',
|
||||
sessionId: parentId || existing?.sessionId || data.sessionId,
|
||||
sessionName: parentSession?.name || parentId || data.sessionId,
|
||||
title: 'Subagent Completed',
|
||||
message: existing?.description || data.description || 'Background agent finished',
|
||||
});
|
||||
this._notifySession(parentId || existing?.sessionId || data.sessionId, 'info', 'subagent-complete', 'Subagent Completed', existing?.description || data.description || 'Background agent finished');
|
||||
|
||||
// Clean up activity/tool data for completed agents after 5 minutes
|
||||
// This prevents memory leaks from long-running sessions with many subagents
|
||||
|
||||
@@ -45,15 +45,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.updateRalphState(data.sessionId, existing);
|
||||
}
|
||||
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'warning',
|
||||
category: 'ralph-complete',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || this.getShortId(data.sessionId),
|
||||
title: 'Loop Complete',
|
||||
message: `Completion: ${data.phrase || 'unknown'}`,
|
||||
});
|
||||
this._notifySession(data.sessionId, 'warning', 'ralph-complete', 'Loop Complete', `Completion: ${data.phrase || 'unknown'}`);
|
||||
},
|
||||
|
||||
_onRalphStatusUpdate(data) {
|
||||
@@ -68,28 +60,12 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.updateRalphState(data.sessionId, { circuitBreaker: data.status });
|
||||
// Notify if circuit breaker opens
|
||||
if (data.status.state === 'OPEN') {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'critical',
|
||||
category: 'circuit-breaker',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || this.getShortId(data.sessionId),
|
||||
title: 'Circuit Breaker Open',
|
||||
message: data.status.reason || 'Loop stuck - no progress detected',
|
||||
});
|
||||
this._notifySession(data.sessionId, 'critical', 'circuit-breaker', 'Circuit Breaker Open', data.status.reason || 'Loop stuck - no progress detected');
|
||||
}
|
||||
},
|
||||
|
||||
_onExitGateMet(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'warning',
|
||||
category: 'exit-gate',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || this.getShortId(data.sessionId),
|
||||
title: 'Exit Gate Met',
|
||||
message: `Loop ready to exit (indicators: ${data.completionIndicators})`,
|
||||
});
|
||||
this._notifySession(data.sessionId, 'warning', 'exit-gate', 'Exit Gate Met', `Loop ready to exit (indicators: ${data.completionIndicators})`);
|
||||
},
|
||||
|
||||
// Bash tools
|
||||
|
||||
@@ -44,21 +44,13 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
_onRespawnBlocked(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
const reasonMap = {
|
||||
circuit_breaker_open: 'Circuit Breaker Open',
|
||||
exit_signal: 'Exit Signal Detected',
|
||||
status_blocked: 'Claude Reported BLOCKED',
|
||||
};
|
||||
const title = reasonMap[data.reason] || 'Respawn Blocked';
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'critical',
|
||||
category: 'respawn-blocked',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || this.getShortId(data.sessionId),
|
||||
title,
|
||||
message: data.details,
|
||||
});
|
||||
this._notifySession(data.sessionId, 'critical', 'respawn-blocked', title, data.details);
|
||||
// Update respawn panel to show blocked state
|
||||
if (data.sessionId === this.activeSessionId) {
|
||||
const stateEl = document.getElementById('respawnStateLabel');
|
||||
@@ -71,14 +63,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
_onRespawnAutoAcceptSent(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'info',
|
||||
category: 'auto-accept',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || this.getShortId(data.sessionId),
|
||||
title: 'Plan Accepted',
|
||||
message: `Accepted plan mode for ${session?.name || 'session'}`,
|
||||
});
|
||||
this._notifySession(data.sessionId, 'info', 'auto-accept', 'Plan Accepted', `Accepted plan mode for ${session?.name || 'session'}`);
|
||||
},
|
||||
|
||||
_onRespawnDetectionUpdate(data) {
|
||||
@@ -144,15 +129,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
_onRespawnError(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'critical',
|
||||
category: 'session-error',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || data.sessionId,
|
||||
title: 'Respawn Error',
|
||||
message: data.error || data.message || 'Respawn encountered an error',
|
||||
});
|
||||
this._notifySession(data.sessionId, 'critical', 'session-error', 'Respawn Error', data.error || data.message || 'Respawn encountered an error');
|
||||
},
|
||||
|
||||
_onRespawnActionLog(data) {
|
||||
|
||||
@@ -14,92 +14,46 @@
|
||||
Object.assign(CodemanApp.prototype, {
|
||||
// Hooks (Claude Code hook events)
|
||||
_onHookIdlePrompt(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
// Always track pending hook - alert will show when switching away from session
|
||||
if (data.sessionId) {
|
||||
this.setPendingHook(data.sessionId, 'idle_prompt');
|
||||
}
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'warning',
|
||||
category: 'hook-idle',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || data.sessionId,
|
||||
title: 'Waiting for Input',
|
||||
message: data.message || 'Claude is idle and waiting for a prompt',
|
||||
});
|
||||
this._notifySession(data.sessionId, 'warning', 'hook-idle', 'Waiting for Input', data.message || 'Claude is idle and waiting for a prompt');
|
||||
},
|
||||
|
||||
_onHookPermissionPrompt(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
// Always track pending hook - action alerts need user interaction to clear
|
||||
if (data.sessionId) {
|
||||
this.setPendingHook(data.sessionId, 'permission_prompt');
|
||||
}
|
||||
const toolInfo = data.tool ? `${data.tool}${data.command ? ': ' + data.command : data.file ? ': ' + data.file : ''}` : '';
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'critical',
|
||||
category: 'hook-permission',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || data.sessionId,
|
||||
title: 'Permission Required',
|
||||
message: toolInfo || 'Claude needs tool approval to continue',
|
||||
});
|
||||
this._notifySession(data.sessionId, 'critical', 'hook-permission', 'Permission Required', toolInfo || 'Claude needs tool approval to continue');
|
||||
},
|
||||
|
||||
_onHookElicitationDialog(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
// Always track pending hook - action alerts need user interaction to clear
|
||||
if (data.sessionId) {
|
||||
this.setPendingHook(data.sessionId, 'elicitation_dialog');
|
||||
}
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'critical',
|
||||
category: 'hook-elicitation',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || data.sessionId,
|
||||
title: 'Question Asked',
|
||||
message: data.question || 'Claude is asking a question and waiting for your answer',
|
||||
});
|
||||
this._notifySession(data.sessionId, 'critical', 'hook-elicitation', 'Question Asked', data.question || 'Claude is asking a question and waiting for your answer');
|
||||
},
|
||||
|
||||
_onHookStop(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
// Clear all pending hooks when Claude finishes responding
|
||||
if (data.sessionId) {
|
||||
this.clearPendingHooks(data.sessionId);
|
||||
}
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'info',
|
||||
category: 'hook-stop',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || data.sessionId,
|
||||
title: 'Response Complete',
|
||||
message: data.reason || 'Claude has finished responding',
|
||||
});
|
||||
this._notifySession(data.sessionId, 'info', 'hook-stop', 'Response Complete', data.reason || 'Claude has finished responding');
|
||||
},
|
||||
|
||||
_onHookTeammateIdle(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'warning',
|
||||
category: 'hook-teammate-idle',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || data.sessionId,
|
||||
title: 'Teammate Idle',
|
||||
message: `A teammate is idle in ${session?.name || data.sessionId}`,
|
||||
});
|
||||
this._notifySession(data.sessionId, 'warning', 'hook-teammate-idle', 'Teammate Idle', `A teammate is idle in ${session?.name || data.sessionId}`);
|
||||
},
|
||||
|
||||
_onHookTaskCompleted(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
this.notificationManager?.notify({
|
||||
urgency: 'info',
|
||||
category: 'hook-task-completed',
|
||||
sessionId: data.sessionId,
|
||||
sessionName: session?.name || data.sessionId,
|
||||
title: 'Task Completed',
|
||||
message: `A team task completed in ${session?.name || data.sessionId}`,
|
||||
});
|
||||
this._notifySession(data.sessionId, 'info', 'hook-task-completed', 'Task Completed', `A team task completed in ${session?.name || data.sessionId}`);
|
||||
},
|
||||
|
||||
|
||||
@@ -517,16 +471,17 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
_updateTunnelUrlDisplay(url) {
|
||||
const row = document.getElementById('tunnelUrlRow');
|
||||
const display = document.getElementById('tunnelUrlDisplay');
|
||||
_updateTunnelUrlRow(rowId, displayId, url, suffix = '') {
|
||||
const row = document.getElementById(rowId);
|
||||
const display = document.getElementById(displayId);
|
||||
if (!row || !display) return;
|
||||
if (url) {
|
||||
const fullUrl = url + suffix;
|
||||
row.style.display = '';
|
||||
display.textContent = url;
|
||||
display.textContent = fullUrl;
|
||||
display.onclick = () => {
|
||||
navigator.clipboard.writeText(url).then(() => {
|
||||
this.showToast('Tunnel URL copied', 'success');
|
||||
navigator.clipboard.writeText(fullUrl).then(() => {
|
||||
this.showToast(`${suffix ? 'Upload' : 'Tunnel'} URL copied`, 'success');
|
||||
});
|
||||
};
|
||||
} else {
|
||||
@@ -534,24 +489,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
display.textContent = '';
|
||||
display.onclick = null;
|
||||
}
|
||||
// Upload URL row
|
||||
const uploadRow = document.getElementById('tunnelUploadUrlRow');
|
||||
const uploadDisplay = document.getElementById('tunnelUploadUrlDisplay');
|
||||
if (!uploadRow || !uploadDisplay) return;
|
||||
if (url) {
|
||||
const uploadUrl = url + '/upload.html';
|
||||
uploadRow.style.display = '';
|
||||
uploadDisplay.textContent = uploadUrl;
|
||||
uploadDisplay.onclick = () => {
|
||||
navigator.clipboard.writeText(uploadUrl).then(() => {
|
||||
this.showToast('Upload URL copied', 'success');
|
||||
});
|
||||
};
|
||||
} else {
|
||||
uploadRow.style.display = 'none';
|
||||
uploadDisplay.textContent = '';
|
||||
uploadDisplay.onclick = null;
|
||||
}
|
||||
},
|
||||
|
||||
_updateTunnelUrlDisplay(url) {
|
||||
this._updateTunnelUrlRow('tunnelUrlRow', 'tunnelUrlDisplay', url);
|
||||
this._updateTunnelUrlRow('tunnelUploadUrlRow', 'tunnelUploadUrlDisplay', url, '/upload.html');
|
||||
},
|
||||
|
||||
showTunnelQR() {
|
||||
|
||||
@@ -185,6 +185,26 @@ export function sanitizeHookData(data: Record<string, unknown> | null | undefine
|
||||
return safeFields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles a service (watcher/manager) on or off based on an enabled flag.
|
||||
* Logs start/stop to console with the given label. Runs an optional callback after starting.
|
||||
*/
|
||||
export function toggleService(
|
||||
enabled: boolean,
|
||||
service: { isRunning(): boolean; start(): void; stop(): void },
|
||||
label: string,
|
||||
onStart?: () => void
|
||||
): void {
|
||||
if (enabled && !service.isRunning()) {
|
||||
service.start();
|
||||
onStart?.();
|
||||
console.log(`${label} started via settings change`);
|
||||
} else if (!enabled && service.isRunning()) {
|
||||
service.stop();
|
||||
console.log(`${label} stopped via settings change`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-configure Ralph tracker for a session.
|
||||
*
|
||||
|
||||
@@ -39,43 +39,37 @@ export function registerOrchestratorRoutes(app: FastifyInstance, ctx: Orchestrat
|
||||
return loop;
|
||||
}
|
||||
|
||||
const EVENT_MAP: [string, (typeof SseEvent)[keyof typeof SseEvent], string[]][] = [
|
||||
['stateChanged', SseEvent.OrchestratorStateChanged, ['state', 'prevState']],
|
||||
['planProgress', SseEvent.OrchestratorPlanProgress, ['phase', 'detail']],
|
||||
['planReady', SseEvent.OrchestratorPlanReady, ['plan']],
|
||||
['phaseStarted', SseEvent.OrchestratorPhaseStarted, ['phase']],
|
||||
['phaseCompleted', SseEvent.OrchestratorPhaseCompleted, ['phase']],
|
||||
['phaseFailed', SseEvent.OrchestratorPhaseFailed, ['phase', 'reason']],
|
||||
['taskAssigned', SseEvent.OrchestratorTaskAssigned, ['task', 'sessionId']],
|
||||
['taskCompleted', SseEvent.OrchestratorTaskCompleted, ['task']],
|
||||
['taskFailed', SseEvent.OrchestratorTaskFailed, ['task', 'error']],
|
||||
['completed', SseEvent.OrchestratorCompleted, ['stats']],
|
||||
];
|
||||
|
||||
let forwardingLoop: import('../../orchestrator-loop.js').OrchestratorLoop | null = null;
|
||||
function setupEventForwarding(loop: import('../../orchestrator-loop.js').OrchestratorLoop) {
|
||||
if (forwardingLoop === loop) return; // Already attached to this loop instance
|
||||
forwardingLoop = loop;
|
||||
loop.on('stateChanged', (state, prevState) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorStateChanged, { state, prevState });
|
||||
});
|
||||
loop.on('planProgress', (phase, detail) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorPlanProgress, { phase, detail });
|
||||
});
|
||||
loop.on('planReady', (plan) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorPlanReady, { plan });
|
||||
});
|
||||
loop.on('phaseStarted', (phase) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorPhaseStarted, { phase });
|
||||
});
|
||||
loop.on('phaseCompleted', (phase) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorPhaseCompleted, { phase });
|
||||
});
|
||||
loop.on('phaseFailed', (phase, reason) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorPhaseFailed, { phase, reason });
|
||||
});
|
||||
for (const [event, sseEvent, argNames] of EVENT_MAP) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
loop.on(event, (...args: any[]) => {
|
||||
const payload: Record<string, unknown> = {};
|
||||
argNames.forEach((name, i) => {
|
||||
payload[name] = args[i];
|
||||
});
|
||||
ctx.broadcast(sseEvent, payload);
|
||||
});
|
||||
}
|
||||
// Special cases with non-trivial payload transforms
|
||||
loop.on('verificationResult', (phase, result) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorVerification, { phaseId: phase.id, result });
|
||||
});
|
||||
loop.on('taskAssigned', (task, sessionId) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorTaskAssigned, { task, sessionId });
|
||||
});
|
||||
loop.on('taskCompleted', (task) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorTaskCompleted, { task });
|
||||
});
|
||||
loop.on('taskFailed', (task, error) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorTaskFailed, { task, error });
|
||||
});
|
||||
loop.on('completed', (stats) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorCompleted, { stats });
|
||||
});
|
||||
loop.on('error', (error) => {
|
||||
ctx.broadcast(SseEvent.OrchestratorError, { error: error.message });
|
||||
});
|
||||
|
||||
@@ -24,7 +24,14 @@ import {
|
||||
import { subagentWatcher } from '../../subagent-watcher.js';
|
||||
import { imageWatcher } from '../../image-watcher.js';
|
||||
import { getLifecycleLog } from '../../session-lifecycle-log.js';
|
||||
import { findSessionOrFail, formatUptime, parseBody, readJsonConfig, SETTINGS_PATH } from '../route-helpers.js';
|
||||
import {
|
||||
findSessionOrFail,
|
||||
formatUptime,
|
||||
parseBody,
|
||||
readJsonConfig,
|
||||
toggleService,
|
||||
SETTINGS_PATH,
|
||||
} from '../route-helpers.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
import type { SessionPort, EventPort, ConfigPort, InfraPort, AuthPort } from '../ports/index.js';
|
||||
import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
|
||||
@@ -281,15 +288,20 @@ export function registerSystemRoutes(
|
||||
|
||||
// ========== Stats ==========
|
||||
|
||||
app.get('/api/stats', async () => {
|
||||
const activeSessionTokens: Record<string, { inputTokens?: number; outputTokens?: number; totalCost?: number }> = {};
|
||||
function collectActiveTokens(): Record<string, { inputTokens?: number; outputTokens?: number; totalCost?: number }> {
|
||||
const tokens: Record<string, { inputTokens?: number; outputTokens?: number; totalCost?: number }> = {};
|
||||
for (const [sessionId, session] of ctx.sessions) {
|
||||
activeSessionTokens[sessionId] = {
|
||||
tokens[sessionId] = {
|
||||
inputTokens: session.inputTokens,
|
||||
outputTokens: session.outputTokens,
|
||||
totalCost: session.totalCost,
|
||||
};
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
app.get('/api/stats', async () => {
|
||||
const activeSessionTokens = collectActiveTokens();
|
||||
return {
|
||||
success: true,
|
||||
stats: ctx.store.getAggregateStats(activeSessionTokens),
|
||||
@@ -298,14 +310,7 @@ export function registerSystemRoutes(
|
||||
});
|
||||
|
||||
app.get('/api/token-stats', async () => {
|
||||
const activeSessionTokens: Record<string, { inputTokens?: number; outputTokens?: number; totalCost?: number }> = {};
|
||||
for (const [sessionId, session] of ctx.sessions) {
|
||||
activeSessionTokens[sessionId] = {
|
||||
inputTokens: session.inputTokens,
|
||||
outputTokens: session.outputTokens,
|
||||
totalCost: session.totalCost,
|
||||
};
|
||||
}
|
||||
const activeSessionTokens = collectActiveTokens();
|
||||
return {
|
||||
success: true,
|
||||
daily: ctx.store.getDailyStats(30),
|
||||
@@ -414,30 +419,17 @@ export function registerSystemRoutes(
|
||||
await fs.writeFile(SETTINGS_PATH, JSON.stringify(merged, null, 2));
|
||||
|
||||
// Handle subagent tracking toggle dynamically
|
||||
const subagentEnabled = settings.subagentTrackingEnabled ?? true;
|
||||
if (subagentEnabled && !subagentWatcher.isRunning()) {
|
||||
subagentWatcher.start();
|
||||
console.log('Subagent watcher started via settings change');
|
||||
} else if (!subagentEnabled && subagentWatcher.isRunning()) {
|
||||
subagentWatcher.stop();
|
||||
console.log('Subagent watcher stopped via settings change');
|
||||
}
|
||||
toggleService((settings.subagentTrackingEnabled as boolean) ?? true, subagentWatcher, 'Subagent watcher');
|
||||
|
||||
// Handle image watcher toggle dynamically
|
||||
const imageWatcherEnabled = settings.imageWatcherEnabled ?? false;
|
||||
if (imageWatcherEnabled && !imageWatcher.isRunning()) {
|
||||
imageWatcher.start();
|
||||
toggleService((settings.imageWatcherEnabled as boolean) ?? false, imageWatcher, 'Image watcher', () => {
|
||||
// Re-watch all active sessions that have image watcher enabled
|
||||
for (const session of ctx.sessions.values()) {
|
||||
if (session.imageWatcherEnabled) {
|
||||
imageWatcher.watchSession(session.id, session.workingDir);
|
||||
}
|
||||
}
|
||||
console.log('Image watcher started via settings change');
|
||||
} else if (!imageWatcherEnabled && imageWatcher.isRunning()) {
|
||||
imageWatcher.stop();
|
||||
console.log('Image watcher stopped via settings change');
|
||||
}
|
||||
});
|
||||
|
||||
// Handle tunnel toggle dynamically
|
||||
if ('tunnelEnabled' in settings) {
|
||||
|
||||
Reference in New Issue
Block a user