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: hook-based real-time session state tracking (like Command app)

libokai5a764ea163b1
diff --git a/CodePulse-macOS/App/CodePulseApp.swift b/CodePulse-macOS/App/CodePulseApp.swift
index 958531b3..00bb856a 100644
--- a/CodePulse-macOS/App/CodePulseApp.swift
+++ b/CodePulse-macOS/App/CodePulseApp.swift
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
NSApp.setActivationPolicy(.accessory)
stateManager = SessionStateManager(scanner: scanner)
+ stateManager.hookServer = hookServer // Connect hook state to state manager
cloudKitSync = CloudKitSync(stateManager: stateManager)
menuBarController = MenuBarController(stateManager: stateManager)
diff --git a/CodePulse-macOS/Services/ClaudeHookServer.swift b/CodePulse-macOS/Services/ClaudeHookServer.swift
index 4a82e955..daa38080 100644
--- a/CodePulse-macOS/Services/ClaudeHookServer.swift
+++ b/CodePulse-macOS/Services/ClaudeHookServer.swift
@@ -4,12 +4,33 @@ import os
private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "HookServer")
+/// Claude Code session state derived from hook events (like Command app)
+enum ClaudeState: String, Sendable {
+ case working
+ case waitingForUser
+ case needsPermission
+}
+
/// Lightweight HTTP server that receives Claude Code hook events for real-time updates.
+/// Tracks per-session Claude state from events (working/waiting/needsPermission).
/// Auto-configures hooks in ~/.claude/settings.json on launch.
final class ClaudeHookServer: @unchecked Sendable {
private var listener: NWListener?
private let port: UInt16
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] = [:]
+
+ /// Thread-safe read of session states
+ var sessionStates: [String: ClaudeState] {
+ lock.lock()
+ defer { lock.unlock() }
+ return _sessionStates
+ }
+
+ /// Called on main thread when any hook event arrives
var onEvent: (@Sendable () -> Void)?
init(port: UInt16 = 19221) {
@@ -38,7 +59,8 @@ final class ClaudeHookServer: @unchecked Sendable {
}
var hooks = root["hooks"] as? [String: Any] ?? [:]
- let events = ["PostToolUse", "Stop", "SessionStart", "SessionEnd"]
+ // Listen to more events for accurate state tracking
+ let events = ["PreToolUse", "PostToolUse", "Stop", "Notification", "SessionStart", "SessionEnd"]
let codePulseHook: [String: Any] = ["type": "http", "url": hookURL]
var changed = false
@@ -111,7 +133,6 @@ final class ClaudeHookServer: @unchecked Sendable {
private func handleConnection(_ connection: NWConnection) {
connection.start(queue: queue)
- // Use a class wrapper to avoid capturing mutable var in Sendable closure
final class DataAccumulator: @unchecked Sendable {
var data = Data()
}
@@ -148,22 +169,62 @@ final class ClaudeHookServer: @unchecked Sendable {
}
private func processRequest(_ data: Data) {
- guard let text = String(data: data, encoding: .utf8) else { return }
-
- var eventName = "unknown"
- if let bodyStart = text.range(of: "\r\n\r\n") {
- let body = String(text[bodyStart.upperBound...])
- if let bodyData = body.data(using: .utf8),
- let json = try? JSONSerialization.jsonObject(with: bodyData) as? [String: Any] {
- eventName = json["hook_event_name"] as? String ?? "unknown"
+ guard let text = String(data: data, encoding: .utf8),
+ let bodyStart = text.range(of: "\r\n\r\n") else { return }
+
+ let body = String(text[bodyStart.upperBound...])
+ guard let bodyData = body.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: bodyData) as? [String: Any] else { return }
+
+ 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
+ default:
+ nil
}
- }
- logger.debug("Hook event: \(eventName)")
+ lock.lock()
+ if let newState {
+ _sessionStates[sessionId] = newState
+ } else if eventName == "SessionEnd" {
+ _sessionStates.removeValue(forKey: sessionId)
+ }
+ lock.unlock()
+
+ logger.debug("Hook: \(eventName) → session \(sessionId.prefix(8))... → \(newState?.rawValue ?? "removed")")
+ } else {
+ logger.debug("Hook: \(eventName) (no session_id)")
+ }
// Trigger immediate rescan on main thread
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
+ }
+ }
+ return .waitingForUser
+ }
}
diff --git a/CodePulse-macOS/Services/SessionStateManager.swift b/CodePulse-macOS/Services/SessionStateManager.swift
index d01407ee..70bff22a 100644
--- a/CodePulse-macOS/Services/SessionStateManager.swift
+++ b/CodePulse-macOS/Services/SessionStateManager.swift
@@ -1,21 +1,25 @@
import Foundation
import Combine
import CodePulseShared
+import os
+
+private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "StateManager")
@MainActor
final class SessionStateManager: ObservableObject {
@Published var sessions: [SessionState] = []
private let scanner: SessionScanner
+ /// Reference to hook server for real-time Claude state
+ var hookServer: ClaudeHookServer?
+
private var cancellables = Set<AnyCancellable>()
- private var jsonlSizes: [String: UInt64] = [:]
- private var jsonlSizeTimestamps: [String: Date] = [:]
private let deviceId = Host.current().localizedName ?? UUID().uuidString
init(scanner: SessionScanner) {
self.scanner = scanner
scanner.$activeSessions
- .debounce(for: .seconds(1), scheduler: RunLoop.main)
+ .debounce(for: .seconds(0.5), scheduler: RunLoop.main)
.sink { [weak self] rawSessions in
self?.updateSessions(from: rawSessions)
}
@@ -23,6 +27,7 @@ final class SessionStateManager: ObservableObject {
}
private func updateSessions(from rawSessions: [String: RawSessionFile]) {
+ let hookStates = hookServer?.sessionStates ?? [:]
var updated: [SessionState] = []
for (sessionId, raw) in rawSessions {
@@ -30,7 +35,9 @@ 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 status = detectStatus(raw: raw, tasks: tasks, jsonlUrl: jsonlUrl)
+
+ // Use hook state as primary source of truth (like Command app)
+ let status = detectStatus(sessionId: sessionId, raw: raw, tasks: tasks, hookState: hookStates[sessionId])
let projectName = URL(fileURLWithPath: raw.cwd).lastPathComponent
let startDate = Date(timeIntervalSince1970: TimeInterval(raw.startedAt) / 1000)
@@ -41,7 +48,6 @@ final class SessionStateManager: ObservableObject {
?? indexEntry?.firstPrompt.map { String($0.prefix(50)) }
?? projectName
- // Only update timestamp if content actually changed
let existingSession = sessions.first { $0.sessionId == sessionId }
let contentChanged = existingSession == nil
|| existingSession?.status != status
@@ -80,27 +86,29 @@ final class SessionStateManager: ObservableObject {
}
}
- sessions = updated.sorted { $0.startedAt > $1.startedAt }
+ let newSessions = updated.sorted { $0.startedAt > $1.startedAt }
+ if newSessions != sessions {
+ sessions = newSessions
+ }
}
- private func detectStatus(raw: RawSessionFile, tasks: [TaskItem], jsonlUrl: URL) -> SessionStatus {
+ private func detectStatus(sessionId: String, raw: RawSessionFile, tasks: [TaskItem], hookState: ClaudeState?) -> SessionStatus {
+ // 1. PID dead → completed
guard PIDChecker.isAlive(pid: raw.pid) else { return .completed }
- if tasks.contains(where: { $0.status == .inProgress }) { return .working }
- let currentSize = JSONLTailReader.fileSize(url: jsonlUrl) ?? 0
- let previousSize = jsonlSizes[raw.sessionId] ?? currentSize
- let lastChange = jsonlSizeTimestamps[raw.sessionId] ?? Date()
-
- if currentSize != previousSize {
- jsonlSizes[raw.sessionId] = currentSize
- jsonlSizeTimestamps[raw.sessionId] = Date()
- return .working
+ // 2. Hook state is the primary source of truth (real-time from Claude Code)
+ if let hookState {
+ switch hookState {
+ case .working: return .working
+ case .waitingForUser: return .needsInput
+ case .needsPermission: return .needsInput
+ }
}
- if Date().timeIntervalSince(lastChange) > 30 {
- return .needsInput
- }
+ // 3. Fallback: check tasks (for sessions started before CodePulse)
+ if tasks.contains(where: { $0.status == .inProgress }) { return .working }
+ // 4. No hook data, no active tasks → idle
return .idle
}
diff --git a/CodePulse.xcodeproj/project.pbxproj b/CodePulse.xcodeproj/project.pbxproj
index eb2b5747..7f63bab1 100644
--- a/CodePulse.xcodeproj/project.pbxproj
+++ b/CodePulse.xcodeproj/project.pbxproj
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
- objectVersion = 77;
+ objectVersion = 63;
objects = {
/* Begin PBXBuildFile section */
@@ -70,7 +70,7 @@
3935CEE144EC8AFCA3AEAEA3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
3B652652FD106495A82565C8 /* CodePulseLiveActivity.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = CodePulseLiveActivity.appex; sourceTree = BUILT_PRODUCTS_DIR; };
3BCD1168005B123A7F9ACB37 /* CodePulseLiveActivityBundle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodePulseLiveActivityBundle.swift; sourceTree = "<group>"; };
- 3EB0548BFADFAFC3616A8C4B /* CodePulse-iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = "CodePulse-iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
+ 3EB0548BFADFAFC3616A8C4B /* CodePulse.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CodePulse.app; sourceTree = BUILT_PRODUCTS_DIR; };
42BAF66F7C50D732B7E69333 /* SessionScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionScanner.swift; sourceTree = "<group>"; };
433D534BFD8D3D76B489B324 /* CodePulse-iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "CodePulse-iOS.entitlements"; sourceTree = "<group>"; };
4A67A3CD19408484AB11BB73 /* CodePulseApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodePulseApp.swift; sourceTree = "<group>"; };
@@ -93,7 +93,7 @@
DA699D0197B8A14FD7D1BDC4 /* SessionListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionListView.swift; sourceTree = "<group>"; };
DF291DF4A4EF932B774F227D /* IOSRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSRootView.swift; sourceTree = "<group>"; };
E25C5CD874B7119D57AB2BB1 /* ClaudeHookServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeHookServer.swift; sourceTree = "<group>"; };
- F033CA1408917B1655BC66D2 /* CodePulseShared */ = {isa = PBXFileReference; lastKnownFileType = folder; name = CodePulseShared; path = CodePulseShared; sourceTree = SOURCE_ROOT; };
+ F033CA1408917B1655BC66D2 /* CodePulseShared */ = {isa = PBXFileReference; lastKnownFileType = folder; path = CodePulseShared; sourceTree = SOURCE_ROOT; };
F19A27E00B1B13A579A950F4 /* CloudKitReceiver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudKitReceiver.swift; sourceTree = "<group>"; };
F71E03612F167D883C324D25 /* SessionStateManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionStateManager.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -129,7 +129,7 @@
04721CC753DB3D170E2C8A15 /* Products */ = {
isa = PBXGroup;
children = (
- 3EB0548BFADFAFC3616A8C4B /* CodePulse-iOS.app */,
+ 3EB0548BFADFAFC3616A8C4B /* CodePulse.app */,
8B5EA7075E9DC97237EF2227 /* CodePulse.app */,
3B652652FD106495A82565C8 /* CodePulseLiveActivity.appex */,
);
@@ -301,7 +301,7 @@
C1CA2B270135307CC4E2724D /* CodePulseShared */,
);
productName = "CodePulse-iOS";
- productReference = 3EB0548BFADFAFC3616A8C4B /* CodePulse-iOS.app */;
+ productReference = 3EB0548BFADFAFC3616A8C4B /* CodePulse.app */;
productType = "com.apple.product-type.application";
};
AD1C1A5F9DF9E66175980B2F /* CodePulse */ = {
@@ -346,7 +346,6 @@
packageReferences = (
2546D0E01391BBF7D36B931E /* XCLocalSwiftPackageReference "CodePulseShared" */,
);
- preferredProjectObjectVersion = 77;
projectDirPath = "";
projectRoot = "";
targets = (
@@ -458,7 +457,10 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = "CodePulse-macOS/App/CodePulse.entitlements";
+ CODE_SIGN_IDENTITY = "Apple Development";
+ CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
+ DEVELOPMENT_TEAM = DEVELOPMENT_TEAM_REDACTED;
ENABLE_APP_SANDBOX = NO;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_LSUIElement = YES;
@@ -470,6 +472,7 @@
MACOSX_DEPLOYMENT_TARGET = 14.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pokai.CodePulse;
PRODUCT_NAME = CodePulse;
+ PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = macosx;
SWIFT_VERSION = 6.0;
};
@@ -480,7 +483,10 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = "CodePulse-macOS/App/CodePulse.entitlements";
+ CODE_SIGN_IDENTITY = "Apple Development";
+ CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
+ DEVELOPMENT_TEAM = DEVELOPMENT_TEAM_REDACTED;
ENABLE_APP_SANDBOX = NO;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_LSUIElement = YES;
@@ -492,6 +498,7 @@
MACOSX_DEPLOYMENT_TARGET = 14.0;
PRODUCT_BUNDLE_IDENTIFIER = com.pokai.CodePulse;
PRODUCT_NAME = CodePulse;
+ PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = macosx;
SWIFT_VERSION = 6.0;
};
@@ -566,6 +573,7 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = "CodePulse-iOS/App/CodePulse-iOS.entitlements";
CODE_SIGN_IDENTITY = "iPhone Developer";
+ DEVELOPMENT_TEAM = DEVELOPMENT_TEAM_REDACTED;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
@@ -591,6 +599,7 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = "CodePulse-iOS/App/CodePulse-iOS.entitlements";
CODE_SIGN_IDENTITY = "iPhone Developer";
+ DEVELOPMENT_TEAM = DEVELOPMENT_TEAM_REDACTED;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;