Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: structured notification_type parsing + lastEvent tracking

libokai8a09cdc2ae19
diff --git a/CodePulse-macOS/Services/ClaudeHookServer.swift b/CodePulse-macOS/Services/ClaudeHookServer.swift
index daa38080..1fdae24f 100644
--- a/CodePulse-macOS/Services/ClaudeHookServer.swift
+++ b/CodePulse-macOS/Services/ClaudeHookServer.swift
@@ -11,8 +11,15 @@ enum ClaudeState: String, Sendable {
case needsPermission
}
+/// Per-session hook state
+struct ClaudeSessionInfo: Sendable {
+ var state: ClaudeState
+ var lastEvent: String // e.g. "Using Bash", "Reading file", "Waiting for input"
+ var toolName: String? // e.g. "Bash", "Read", "Edit", "Write"
+}
+
/// Lightweight HTTP server that receives Claude Code hook events for real-time updates.
-/// Tracks per-session Claude state from events (working/waiting/needsPermission).
+/// Tracks per-session Claude state + lastEvent from events (working/waiting/needsPermission).
/// Auto-configures hooks in ~/.claude/settings.json on launch.
final class ClaudeHookServer: @unchecked Sendable {
private var listener: NWListener?
@@ -20,17 +27,21 @@ final class ClaudeHookServer: @unchecked Sendable {
private let queue = DispatchQueue(label: "com.pokai.CodePulse.hooks", qos: .utility)
private let lock = NSLock()
- /// session_id -> ClaudeState, updated from hook events. Access via sessionStates computed property.
- private var _sessionStates: [String: ClaudeState] = [:]
+ private var _sessions: [String: ClaudeSessionInfo] = [:]
- /// Thread-safe read of session states
- var sessionStates: [String: ClaudeState] {
+ /// Thread-safe read of session info
+ var sessions: [String: ClaudeSessionInfo] {
lock.lock()
defer { lock.unlock() }
- return _sessionStates
+ return _sessions
+ }
+
+ /// Convenience: just the states
+ var sessionStates: [String: ClaudeState] {
+ let s = sessions
+ return s.mapValues { $0.state }
}
- /// Called on main thread when any hook event arrives
var onEvent: (@Sendable () -> Void)?
init(port: UInt16 = 19221) {
@@ -59,11 +70,23 @@ final class ClaudeHookServer: @unchecked Sendable {
}
var hooks = root["hooks"] as? [String: Any] ?? [:]
- // Listen to more events for accurate state tracking
- let events = ["PreToolUse", "PostToolUse", "Stop", "Notification", "SessionStart", "SessionEnd"]
+ let events = ["PreToolUse", "Stop", "Notification", "SessionStart", "SessionEnd"]
let codePulseHook: [String: Any] = ["type": "http", "url": hookURL]
var changed = false
+ // Clean up stale PostToolUse hooks if present (no longer needed)
+ if var postEntries = hooks["PostToolUse"] as? [[String: Any]] {
+ let before = postEntries.count
+ postEntries.removeAll { entry in
+ guard let entryHooks = entry["hooks"] as? [[String: Any]] else { return false }
+ return entryHooks.contains { ($0["url"] as? String) == hookURL }
+ }
+ if postEntries.count != before {
+ hooks["PostToolUse"] = postEntries.isEmpty ? nil : postEntries
+ changed = true
+ }
+ }
+
for event in events {
var entries = hooks[event] as? [[String: Any]] ?? []
let alreadyPresent = entries.contains { entry in
@@ -168,6 +191,8 @@ final class ClaudeHookServer: @unchecked Sendable {
receiveMore()
}
+ // MARK: - Event Processing
+
private func processRequest(_ data: Data) {
guard let text = String(data: data, encoding: .utf8),
let bodyStart = text.range(of: "\r\n\r\n") else { return }
@@ -179,52 +204,73 @@ final class ClaudeHookServer: @unchecked Sendable {
let eventName = json["hook_event_name"] as? String ?? "unknown"
let sessionId = json["session_id"] as? String
- // Derive Claude state from event (same logic as Command app)
- if let sessionId {
- let newState: ClaudeState? = switch eventName {
- case "SessionStart", "PreToolUse", "PostToolUse":
- .working
- case "Stop":
- .waitingForUser
- case "Notification":
- parseNotificationState(json)
- case "SessionEnd":
- nil // remove session
+ guard let sessionId else {
+ logger.debug("Hook: \(eventName) (no session_id)")
+ DispatchQueue.main.async { [weak self] in self?.onEvent?() }
+ return
+ }
+
+ let toolName = json["tool_name"] as? String
+
+ switch eventName {
+ case "SessionStart":
+ updateSession(sessionId, state: .working, lastEvent: "Session started")
+
+ case "PreToolUse":
+ let displayTool = formatToolName(toolName)
+ updateSession(sessionId, state: .working, lastEvent: "Using \(displayTool)", toolName: toolName)
+
+ case "Stop":
+ updateSession(sessionId, state: .waitingForUser, lastEvent: "Waiting for input")
+
+ case "Notification":
+ let notificationType = json["notification_type"] as? String
+ ?? (json["message"] as? [String: Any])?["notification_type"] as? String
+
+ switch notificationType {
+ case "permission_prompt":
+ updateSession(sessionId, state: .needsPermission, lastEvent: "Needs permission")
+ case "idle_prompt":
+ updateSession(sessionId, state: .waitingForUser, lastEvent: "Waiting for input")
default:
- nil
+ // Don't change state for unknown notifications
+ logger.debug("Hook: Notification type=\(notificationType ?? "nil") for \(sessionId.prefix(8))...")
}
+ case "SessionEnd":
lock.lock()
- if let newState {
- _sessionStates[sessionId] = newState
- } else if eventName == "SessionEnd" {
- _sessionStates.removeValue(forKey: sessionId)
- }
+ _sessions.removeValue(forKey: sessionId)
lock.unlock()
+ logger.debug("Hook: SessionEnd → session \(sessionId.prefix(8))... removed")
- logger.debug("Hook: \(eventName) → session \(sessionId.prefix(8))... → \(newState?.rawValue ?? "removed")")
- } else {
- logger.debug("Hook: \(eventName) (no session_id)")
+ default:
+ logger.debug("Hook: unknown event \(eventName)")
}
- // Trigger immediate rescan on main thread
- DispatchQueue.main.async { [weak self] in
- self?.onEvent?()
- }
+ DispatchQueue.main.async { [weak self] in self?.onEvent?() }
}
- private func parseNotificationState(_ json: [String: Any]) -> ClaudeState {
- // Check notification type for permission prompts
- if let message = json["message"] as? String {
- if message.contains("permission") {
- return .needsPermission
- }
- }
- if let type = json["type"] as? String {
- if type.contains("permission") {
- return .needsPermission
- }
+ private func updateSession(_ sessionId: String, state: ClaudeState, lastEvent: String, toolName: String? = nil) {
+ lock.lock()
+ _sessions[sessionId] = ClaudeSessionInfo(state: state, lastEvent: lastEvent, toolName: toolName)
+ lock.unlock()
+ logger.debug("Hook: \(lastEvent) → session \(sessionId.prefix(8))... → \(state.rawValue)")
+ }
+
+ private func formatToolName(_ name: String?) -> String {
+ guard let name else { return "tool" }
+ switch name {
+ case "Bash": return "Bash"
+ case "Read": return "Read"
+ case "Edit": return "Edit"
+ case "Write": return "Write"
+ case "Glob": return "Glob"
+ case "Grep": return "Grep"
+ case "Agent": return "Agent"
+ case "TodoWrite", "TaskCreate", "TaskUpdate": return "Tasks"
+ case "WebFetch": return "WebFetch"
+ case "WebSearch": return "WebSearch"
+ default: return name
}
- return .waitingForUser
}
}
diff --git a/CodePulse-macOS/Services/SessionStateManager.swift b/CodePulse-macOS/Services/SessionStateManager.swift
index 70bff22a..343275a8 100644
--- a/CodePulse-macOS/Services/SessionStateManager.swift
+++ b/CodePulse-macOS/Services/SessionStateManager.swift
@@ -27,7 +27,7 @@ final class SessionStateManager: ObservableObject {
}
private func updateSessions(from rawSessions: [String: RawSessionFile]) {
- let hookStates = hookServer?.sessionStates ?? [:]
+ let hookSessions = hookServer?.sessions ?? [:]
var updated: [SessionState] = []
for (sessionId, raw) in rawSessions {
@@ -35,14 +35,16 @@ final class SessionStateManager: ObservableObject {
let indexEntry = SessionFileParser.parseSessionIndex(cwd: raw.cwd, sessionId: sessionId)
let jsonlUrl = ClaudePaths.jsonlPath(cwd: raw.cwd, sessionId: sessionId)
let jsonlInfo = JSONLTailReader.extractInfo(url: jsonlUrl)
+ let hookInfo = hookSessions[sessionId]
// Use hook state as primary source of truth (like Command app)
- let status = detectStatus(sessionId: sessionId, raw: raw, tasks: tasks, hookState: hookStates[sessionId])
+ let status = detectStatus(sessionId: sessionId, raw: raw, tasks: tasks, hookState: hookInfo?.state)
let projectName = URL(fileURLWithPath: raw.cwd).lastPathComponent
let startDate = Date(timeIntervalSince1970: TimeInterval(raw.startedAt) / 1000)
let duration = Int(Date().timeIntervalSince(startDate))
let currentTask = tasks.first(where: { $0.status == .inProgress })?.activeForm
+ let lastEvent = hookInfo?.lastEvent
let summary = indexEntry?.summary
?? indexEntry?.firstPrompt.map { String($0.prefix(50)) }
@@ -54,6 +56,7 @@ final class SessionStateManager: ObservableObject {
|| existingSession?.tasks != tasks
|| existingSession?.contextPct != jsonlInfo.contextPct
|| existingSession?.currentTask != currentTask
+ || existingSession?.lastEvent != lastEvent
let updatedAt = contentChanged ? Date() : (existingSession?.updatedAt ?? Date())
@@ -65,6 +68,7 @@ final class SessionStateManager: ObservableObject {
model: formatModel(jsonlInfo.model),
summary: summary,
currentTask: currentTask,
+ lastEvent: lastEvent,
tasks: tasks,
contextPct: jsonlInfo.contextPct,
costUSD: jsonlInfo.costUSD,
diff --git a/CodePulse-macOS/Views/SessionRowView.swift b/CodePulse-macOS/Views/SessionRowView.swift
index 4154b194..a9e517e2 100644
--- a/CodePulse-macOS/Views/SessionRowView.swift
+++ b/CodePulse-macOS/Views/SessionRowView.swift
@@ -14,19 +14,21 @@ struct SessionRowView: View {
.font(.system(size: 13, weight: isHovered ? .medium : .regular))
.foregroundStyle(.primary)
.lineLimit(1)
+
+ // Show lastEvent or status subtitle
+ if let subtitle = subtitleText {
+ Text(subtitle)
+ .font(.system(size: 11))
+ .foregroundStyle(subtitleColor)
+ .lineLimit(1)
+ }
}
Spacer(minLength: 4)
- if session.status == .needsInput {
- Text("needs input")
- .font(.system(size: 10))
- .foregroundStyle(.orange)
- } else {
- Text(relativeTime(session.startedAt))
- .font(.system(size: 11, design: .rounded))
- .foregroundStyle(.tertiary)
- }
+ Text(relativeTime(session.startedAt))
+ .font(.system(size: 11, design: .rounded))
+ .foregroundStyle(.tertiary)
}
.padding(.horizontal, 8)
.padding(.vertical, 6)
@@ -38,6 +40,25 @@ struct SessionRowView: View {
.contentShape(Rectangle())
}
+ private var subtitleText: String? {
+ if let lastEvent = session.lastEvent {
+ return lastEvent
+ }
+ if let currentTask = session.currentTask {
+ return currentTask
+ }
+ return nil
+ }
+
+ private var subtitleColor: Color {
+ switch session.status {
+ case .working: return .green
+ case .needsInput: return .orange
+ case .error: return .red
+ default: return .secondary
+ }
+ }
+
private func relativeTime(_ date: Date) -> String {
let seconds = -date.timeIntervalSinceNow
if seconds < 60 { return "now" }
diff --git a/CodePulseShared/Sources/Models/SessionState.swift b/CodePulseShared/Sources/Models/SessionState.swift
index 4ea9fd9c..ff8a6dcd 100644
--- a/CodePulseShared/Sources/Models/SessionState.swift
+++ b/CodePulseShared/Sources/Models/SessionState.swift
@@ -8,6 +8,7 @@ public struct SessionState: Codable, Identifiable, Equatable, Sendable {
public var model: String
public var summary: String
public var currentTask: String?
+ public var lastEvent: String?
public var tasks: [TaskItem]
public var contextPct: Int
public var costUSD: Double
@@ -33,7 +34,7 @@ public struct SessionState: Codable, Identifiable, Equatable, Sendable {
public init(
sessionId: String, projectName: String, gitBranch: String,
status: SessionStatus, model: String, summary: String,
- currentTask: String? = nil, tasks: [TaskItem] = [],
+ currentTask: String? = nil, lastEvent: String? = nil, tasks: [TaskItem] = [],
contextPct: Int = 0, costUSD: Double = 0,
startedAt: Date = Date(), durationSec: Int = 0,
deviceId: String = "", updatedAt: Date = Date()
@@ -45,6 +46,7 @@ public struct SessionState: Codable, Identifiable, Equatable, Sendable {
self.model = model
self.summary = summary
self.currentTask = currentTask
+ self.lastEvent = lastEvent
self.tasks = tasks
self.contextPct = contextPct
self.costUSD = costUSD