Files
agent-ui/server/routes/claude-hook.ts
josedario87 25bca2625b feat: centralized PTY-scoped session state, sync engine debug panel, lifecycle states, WS monitor
- Refactor session state to use ptySessionId as primary key across all components
- Add SessionStateManager with PTY-scoped hook processing, approval tracking, notifications
- Add sync-engine debug panel (AgentStatesSection, HookTimelineSection, TerminalRegistrySection, WsMonitorSection)
- Add useLifecycleStates composable for continuous state chips (session, responding, tool, subagent, compacting)
- Add WS monitor endpoint and composable for real-time connection health
- Enhance SessionLifecycleStatus with animated state chips and badge counts
- Enhance SystemMessage with expanded content and better formatting
- Update hooks (approval-permission, approval-plan, notify) with pty_session injection
- Update approval system to derive pending lists from PTY-scoped state
- Update ChatContainer with PTY-derived agent status and lifecycle events
- Update AgentBadge with PTY-scoped status colors
- Improve PiP window, approval window, and loading window handling
2026-02-24 20:10:31 -06:00

102 lines
3.9 KiB
TypeScript

import { jsonResponse, errorResponse } from '../utils/cors'
import { PORT_TERMINAL } from '../config'
import { existsSync, readFileSync } from 'fs'
import { setActiveSession, getIncrementalMessages } from '../services/transcript-engine'
import { sessionState, type HookPayload } from '../services/session-state'
export async function handleClaudeHook(req: Request): Promise<Response | null> {
if (req.method !== 'POST') return null
try {
const url = new URL(req.url)
let agent = url.searchParams.get('agent') || ''
const body = await req.json() as HookPayload
// Read PTY session ID from env-injected query param
const ptySession = url.searchParams.get('pty_session') || ''
// Auto-detect agent from session_id or transcript_path
if (!agent && body.session_id) {
agent = sessionState.findAgentBySessionId(body.session_id) || ''
}
if (!agent && body.transcript_path) {
const matches = sessionState.findAgentsByTranscript(body.transcript_path as string)
if (matches.length === 1) agent = matches[0]
}
if (!agent) agent = 'claude'
// On Stop events, extract last assistant response from transcript
if (body.hook_event_name === 'Stop' && body.transcript_path) {
try {
let tp = body.transcript_path as string
// Normalize path for Windows (handle both C:\ and /c/ formats)
tp = tp.replace(/\\/g, '/')
if (/^\/[a-zA-Z]\//.test(tp)) {
tp = tp[1].toUpperCase() + ':' + tp.slice(2)
}
if (existsSync(tp)) {
const lines = readFileSync(tp, 'utf8').trim().split('\n')
for (let i = lines.length - 1; i >= Math.max(0, lines.length - 30); i--) {
try {
const obj = JSON.parse(lines[i])
if (obj.type === 'assistant' && obj.message?.role === 'assistant') {
const content = obj.message.content
if (Array.isArray(content)) {
const text = content.filter((c: any) => c.type === 'text').map((c: any) => c.text).join('\n')
if (text) {
body.assistant_response = text.slice(0, 500)
break
}
}
}
} catch { /* skip unparseable lines */ }
}
}
} catch (e) {
console.error('[claude-hook] Failed to read transcript:', e)
}
}
// Inject agent name and PTY session into hook data for WS consumers
const hookData = { ...body, agent_name: agent, pty_session: ptySession }
// 1. Broadcast full hook data via WebSocket (always, even for subagents)
try {
await fetch(`http://localhost:${PORT_TERMINAL}/claude-hook`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(hookData)
})
} catch (e) {
console.error('[claude-hook] Failed to forward hook to terminal server:', e)
}
// 2. Incremental transcript reading for real-time chat
if (body.session_id && body.transcript_path) {
setActiveSession(agent, body.session_id, body.transcript_path as string)
const newMessages = getIncrementalMessages(body.session_id, body.transcript_path as string)
if (newMessages.length > 0) {
try {
await fetch(`http://localhost:${PORT_TERMINAL}/transcript-update`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: body.session_id,
agent,
messages: newMessages,
hookEvent: body.hook_event_name
})
})
} catch (e) {
console.error('[claude-hook] Failed to forward transcript update:', e)
}
}
}
return jsonResponse({ success: true, event: body.hook_event_name, agent })
} catch (e) {
return errorResponse('Invalid JSON body', 400)
}
}