feat: Rich hook forwarding, permission bridge, and toast notifications
Replace hardcoded PowerShell status hooks with stdin-forwarding hooks that send full Claude Code hook data (tool_input, tool_response, prompt, session_id, model, etc.) to /api/claude-hook endpoint. - PowerShell hooks read stdin JSON and POST to /api/claude-hook - Server derives status for backward-compat FAB animations - Server extracts assistant_response from transcript on Stop events - New /api/claude-permission endpoint with Promise-based allow/deny flow - HookNotifications.vue: toast system showing session, prompt, tool use, tool results, notifications, and final assistant response - WebSocket broadcast for claude-hook and claude-permission message types
This commit is contained in:
125
server/routes/claude-hook.ts
Normal file
125
server/routes/claude-hook.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { jsonResponse, errorResponse } from '../utils/cors'
|
||||
import { PORT_TERMINAL } from '../config'
|
||||
import { existsSync, readFileSync } from 'fs'
|
||||
|
||||
type ClaudeStatus = 'idle' | 'processing' | 'toolUse' | 'toolDone' | 'reading' | 'writing' | 'sessionStart' | 'subagentStart' | 'subagentStop' | 'notification' | 'permissionRequest' | 'thinking'
|
||||
|
||||
interface HookPayload {
|
||||
hook_event_name?: string
|
||||
session_id?: string
|
||||
tool_name?: string
|
||||
tool_input?: unknown
|
||||
tool_response?: unknown
|
||||
prompt?: string
|
||||
cwd?: string
|
||||
model?: string
|
||||
source?: string
|
||||
transcript_path?: string
|
||||
message?: string
|
||||
notification_type?: string
|
||||
stop_hook_active?: boolean
|
||||
tool_use_id?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
function deriveStatus(payload: HookPayload): { status: ClaudeStatus, tool?: string } {
|
||||
const event = payload.hook_event_name
|
||||
const toolName = payload.tool_name
|
||||
|
||||
switch (event) {
|
||||
case 'SessionStart':
|
||||
return { status: 'sessionStart' }
|
||||
case 'UserPromptSubmit':
|
||||
return { status: 'processing' }
|
||||
case 'PreToolUse':
|
||||
if (toolName && /^(Read|Glob|Grep)$/.test(toolName)) {
|
||||
return { status: 'reading', tool: toolName }
|
||||
}
|
||||
if (toolName && /^(Edit|Write)$/.test(toolName)) {
|
||||
return { status: 'writing', tool: toolName }
|
||||
}
|
||||
return { status: 'toolUse', tool: toolName }
|
||||
case 'PostToolUse':
|
||||
return { status: 'toolDone', tool: toolName }
|
||||
case 'PermissionRequest':
|
||||
return { status: 'permissionRequest', tool: toolName }
|
||||
case 'Notification':
|
||||
return { status: 'notification' }
|
||||
case 'Stop':
|
||||
return { status: 'idle' }
|
||||
default:
|
||||
return { status: 'processing' }
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleClaudeHook(req: Request): Promise<Response | null> {
|
||||
if (req.method !== 'POST') return null
|
||||
|
||||
try {
|
||||
const url = new URL(req.url)
|
||||
const agent = url.searchParams.get('agent') || ''
|
||||
const body = await req.json() as HookPayload
|
||||
|
||||
// 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 into hook data for WS consumers
|
||||
const hookData = { ...body, agent_name: agent || 'main' }
|
||||
|
||||
// 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. Derive status and broadcast for backward compat (App.vue/AgentBar.vue)
|
||||
const { status, tool } = deriveStatus(body)
|
||||
try {
|
||||
await fetch(`http://localhost:${PORT_TERMINAL}/claude-status`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status, tool, agent: agent || 'main' })
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('[claude-hook] Failed to forward status to terminal server:', e)
|
||||
}
|
||||
|
||||
return jsonResponse({ success: true, event: body.hook_event_name, agent: agent || 'main' })
|
||||
} catch (e) {
|
||||
return errorResponse('Invalid JSON body', 400)
|
||||
}
|
||||
}
|
||||
111
server/routes/claude-permission.ts
Normal file
111
server/routes/claude-permission.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { jsonResponse, errorResponse } from '../utils/cors'
|
||||
import { PORT_TERMINAL } from '../config'
|
||||
|
||||
interface PermissionPayload {
|
||||
hook_event_name?: string
|
||||
session_id?: string
|
||||
tool_name?: string
|
||||
tool_input?: unknown
|
||||
cwd?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
interface PendingPermission {
|
||||
resolve: (decision: string) => void
|
||||
timer: ReturnType<typeof setTimeout>
|
||||
payload: PermissionPayload
|
||||
}
|
||||
|
||||
// Map of requestId -> pending permission promise resolver
|
||||
const pendingPermissions = new Map<string, PendingPermission>()
|
||||
|
||||
const PERMISSION_TIMEOUT_MS = 60_000
|
||||
|
||||
export async function handleClaudePermission(req: Request): Promise<Response | null> {
|
||||
if (req.method !== 'POST') return null
|
||||
|
||||
try {
|
||||
const body = await req.json() as PermissionPayload
|
||||
const requestId = `perm_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
|
||||
|
||||
// Broadcast permission request to UI via WebSocket
|
||||
try {
|
||||
await fetch(`http://localhost:${PORT_TERMINAL}/claude-permission`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId, ...body })
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('[claude-permission] Failed to broadcast to terminal server:', e)
|
||||
}
|
||||
|
||||
// Also broadcast claude-status for backward compat (animations)
|
||||
try {
|
||||
await fetch(`http://localhost:${PORT_TERMINAL}/claude-status`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: 'permissionRequest', tool: body.tool_name })
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('[claude-permission] Failed to forward status:', e)
|
||||
}
|
||||
|
||||
// Wait for UI decision (or timeout)
|
||||
const decision = await new Promise<string>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
pendingPermissions.delete(requestId)
|
||||
resolve('ask')
|
||||
}, PERMISSION_TIMEOUT_MS)
|
||||
|
||||
pendingPermissions.set(requestId, { resolve, timer, payload: body })
|
||||
})
|
||||
|
||||
return jsonResponse({ decision, requestId })
|
||||
} catch (e) {
|
||||
return errorResponse('Invalid JSON body', 400)
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleClaudePermissionRespond(req: Request): Promise<Response | null> {
|
||||
if (req.method !== 'POST') return null
|
||||
|
||||
try {
|
||||
const body = await req.json() as { requestId: string, decision: 'allow' | 'deny' }
|
||||
|
||||
if (!body.requestId || !body.decision) {
|
||||
return errorResponse('Missing requestId or decision', 400)
|
||||
}
|
||||
|
||||
if (!['allow', 'deny'].includes(body.decision)) {
|
||||
return errorResponse('Decision must be "allow" or "deny"', 400)
|
||||
}
|
||||
|
||||
const pending = pendingPermissions.get(body.requestId)
|
||||
if (!pending) {
|
||||
return errorResponse('Permission request not found or already expired', 404)
|
||||
}
|
||||
|
||||
// Resolve the pending promise
|
||||
clearTimeout(pending.timer)
|
||||
pendingPermissions.delete(body.requestId)
|
||||
pending.resolve(body.decision)
|
||||
|
||||
return jsonResponse({ success: true, requestId: body.requestId, decision: body.decision })
|
||||
} catch (e) {
|
||||
return errorResponse('Invalid JSON body', 400)
|
||||
}
|
||||
}
|
||||
|
||||
// List pending permissions (useful for UI to recover state)
|
||||
export async function handleClaudePermissionList(req: Request): Promise<Response | null> {
|
||||
if (req.method !== 'GET') return null
|
||||
|
||||
const pending = Array.from(pendingPermissions.entries()).map(([id, p]) => ({
|
||||
requestId: id,
|
||||
tool_name: p.payload.tool_name,
|
||||
tool_input: p.payload.tool_input,
|
||||
session_id: p.payload.session_id
|
||||
}))
|
||||
|
||||
return jsonResponse({ pending })
|
||||
}
|
||||
@@ -10,9 +10,16 @@ import { handleTables, handleStats, handleTableSchema, handleTableData, handleQu
|
||||
import { handleWhisperRoutes } from './whisper'
|
||||
import { handleRecordingsRoutes } from './recordings'
|
||||
import { handleClaudeStatus } from './claude-status'
|
||||
import { handleClaudeHook } from './claude-hook'
|
||||
import { handleClaudePermission, handleClaudePermissionRespond, handleClaudePermissionList } from './claude-permission'
|
||||
import { handleSnapshots, handleSnapshotById } from './snapshots'
|
||||
import { handleGitStatus, handleGitDiff, handleGitLog, handleGitLogCommit, handleGitCompare, handleGitBranches, handleGitCurrentBranch, handleGitTree, handleGitFile } from './git'
|
||||
import { handleAgents, handleAgentsFile } from './agents'
|
||||
import {
|
||||
handleAgents, handleAgentsFile,
|
||||
handleAgentsConfig, handleAgentsKnownTools, handleAgentsSkills,
|
||||
handleAgentsPlugins, handleAgentsMcpJson,
|
||||
handleAgentsConfigPermissions, handleAgentsConfigHooks, handleAgentsConfigMcp
|
||||
} from './agents'
|
||||
|
||||
export async function handleRequest(req: Request): Promise<Response> {
|
||||
const url = new URL(req.url)
|
||||
@@ -58,6 +65,28 @@ export async function handleRequest(req: Request): Promise<Response> {
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
// Claude Code hook (rich stdin data forwarding)
|
||||
if (path === '/api/claude-hook') {
|
||||
const res = await handleClaudeHook(req)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
// Claude Code permission request/respond
|
||||
if (path === '/api/claude-permission') {
|
||||
if (req.method === 'GET') {
|
||||
const res = await handleClaudePermissionList(req)
|
||||
if (res) return res
|
||||
} else {
|
||||
const res = await handleClaudePermission(req)
|
||||
if (res) return res
|
||||
}
|
||||
}
|
||||
|
||||
if (path === '/api/claude-permission-respond') {
|
||||
const res = await handleClaudePermissionRespond(req)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
// Components
|
||||
if (path === '/api/components') {
|
||||
const res = await handleComponents(req)
|
||||
@@ -253,6 +282,46 @@ export async function handleRequest(req: Request): Promise<Response> {
|
||||
return handleAgents(req)
|
||||
}
|
||||
|
||||
if (path === '/api/agents/config' && req.method === 'GET') {
|
||||
const res = await handleAgentsConfig(req, url)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
if (path === '/api/agents/known-tools' && req.method === 'GET') {
|
||||
const res = await handleAgentsKnownTools(req)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
if (path === '/api/agents/skills' && req.method === 'GET') {
|
||||
const res = await handleAgentsSkills(req, url)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
if (path === '/api/agents/plugins' && req.method === 'GET') {
|
||||
const res = await handleAgentsPlugins(req)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
if (path === '/api/agents/mcp-json' && req.method === 'GET') {
|
||||
const res = await handleAgentsMcpJson(req)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
if (path === '/api/agents/config/permissions' && req.method === 'POST') {
|
||||
const res = await handleAgentsConfigPermissions(req)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
if (path === '/api/agents/config/hooks' && req.method === 'POST') {
|
||||
const res = await handleAgentsConfigHooks(req)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
if (path === '/api/agents/config/mcp' && req.method === 'POST') {
|
||||
const res = await handleAgentsConfigMcp(req)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
if (path === '/api/agents/file') {
|
||||
const res = await handleAgentsFile(req, url)
|
||||
if (res) return res
|
||||
|
||||
@@ -124,6 +124,28 @@ export function startTerminalServer() {
|
||||
}
|
||||
}
|
||||
|
||||
// Claude hook broadcast endpoint (rich data from stdin)
|
||||
if (url.pathname === '/claude-hook' && req.method === 'POST') {
|
||||
try {
|
||||
const body = await req.json()
|
||||
broadcastClaudeHook(body)
|
||||
return Response.json({ success: true }, { headers: corsHeaders })
|
||||
} catch {
|
||||
return Response.json({ error: 'Invalid JSON' }, { status: 400, headers: corsHeaders })
|
||||
}
|
||||
}
|
||||
|
||||
// Claude permission request broadcast endpoint
|
||||
if (url.pathname === '/claude-permission' && req.method === 'POST') {
|
||||
try {
|
||||
const body = await req.json()
|
||||
broadcastPermissionRequest(body)
|
||||
return Response.json({ success: true }, { headers: corsHeaders })
|
||||
} catch {
|
||||
return Response.json({ error: 'Invalid JSON' }, { status: 400, headers: corsHeaders })
|
||||
}
|
||||
}
|
||||
|
||||
// Check if this is a WebSocket upgrade request
|
||||
const upgradeHeader = req.headers.get('upgrade')
|
||||
console.log(`[Terminal] Request: ${req.method} ${url.pathname}, Upgrade: ${upgradeHeader}`)
|
||||
@@ -269,3 +291,49 @@ export function broadcastClaudeStatus(status: ClaudeStatus, tool?: string, agent
|
||||
|
||||
console.log(`[Terminal] Claude status broadcast: ${status}${tool ? ` (${tool})` : ''} → ${clientCount} clients`)
|
||||
}
|
||||
|
||||
// Broadcast full Claude hook data to ALL clients
|
||||
export function broadcastClaudeHook(data: Record<string, unknown>) {
|
||||
const message = JSON.stringify({
|
||||
type: 'claude-hook',
|
||||
...data,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
|
||||
let clientCount = 0
|
||||
for (const [, session] of sessions) {
|
||||
for (const ws of session.clients) {
|
||||
try {
|
||||
ws.send(message)
|
||||
clientCount++
|
||||
} catch {
|
||||
// Client disconnected, ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Terminal] Claude hook broadcast: ${data.hook_event_name || 'unknown'}${data.tool_name ? ` (${data.tool_name})` : ''} → ${clientCount} clients`)
|
||||
}
|
||||
|
||||
// Broadcast permission request to ALL clients
|
||||
export function broadcastPermissionRequest(data: Record<string, unknown>) {
|
||||
const message = JSON.stringify({
|
||||
type: 'claude-permission',
|
||||
...data,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
|
||||
let clientCount = 0
|
||||
for (const [, session] of sessions) {
|
||||
for (const ws of session.clients) {
|
||||
try {
|
||||
ws.send(message)
|
||||
clientCount++
|
||||
} catch {
|
||||
// Client disconnected, ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Terminal] Permission request broadcast: ${data.tool_name || 'unknown'} (${data.requestId}) → ${clientCount} clients`)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user