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-driven status detection inspired by cc-status-bar

libokai80389940236b
diff --git a/CLAUDE.md b/CLAUDE.md
index 50c2f0ba..73cbd2cd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -11,12 +11,13 @@
## Architecture
- macOS menu bar app using `NSStatusItem` + `NSPopover`
-- **JSONL transcript parsing** (like Pixel Agents) for state detection — zero impact on Claude Code
-- Single `Notification` command hook (`~/.codepulse/notify.sh`) for instant permission detection only
+- **Hook-driven status detection** — 7 Claude Code hooks (Notification, Stop, UserPromptSubmit, PreToolUse, PostToolUse, SessionStart, SessionEnd) provide instant, accurate state
+- JSONL transcript parsing retained for supplementary data only (model, tokens, cost, tool display)
+- Command hook script (`~/.codepulse/notify.sh`) reads stdin, POSTs to local server, exits instantly (~20ms)
- Shell script hook uses `curl --max-time 1 || true` — never blocks Claude Code even if app is not running
- Shared code in `CodePulseShared` Swift Package (macOS 14+ / iOS 17+)
- **Do NOT register HTTP hooks** — they block Claude Code on ECONNREFUSED when app is down
-- **Do NOT register PreToolUse or PostToolUse hooks** — they are synchronous and block tool execution
+- Command hooks for PreToolUse/PostToolUse are safe — script exits in <20ms, imperceptible delay
## Targets
diff --git a/CodePulse-macOS/App/CodePulseApp.swift b/CodePulse-macOS/App/CodePulseApp.swift
index 566a9069..07d5a4f8 100644
--- a/CodePulse-macOS/App/CodePulseApp.swift
+++ b/CodePulse-macOS/App/CodePulseApp.swift
@@ -25,31 +25,29 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.setActivationPolicy(.accessory)
+ scanner.hookServer = hookServer
stateManager = SessionStateManager(scanner: scanner)
stateManager.hookServer = hookServer
cloudKitSync = CloudKitSync(stateManager: stateManager)
menuBarController = MenuBarController(stateManager: stateManager)
- // Hook events: Notification, PermissionRequest, PreCompact, SessionStart, SessionEnd
hookServer.ensureHooksConfigured()
- hookServer.onPermissionEvent = { [weak self] in
- self?.scanner.scan()
- }
+ // SessionStart/SessionEnd: immediate refresh (new/removed session)
hookServer.onSessionEvent = { [weak self] in
- self?.scanner.scan()
+ self?.stateManager.refreshFromHookState()
}
- hookServer.onHookSignal = { [weak self] sessionId, signalType, toolName in
+ // All other hooks: immediate refresh with hook signal applied first
+ hookServer.onHookSignal = { [weak self] sessionId, signal, toolName in
self?.stateManager.transcriptWatcher.handleHookSignal(
- sessionId: sessionId, signalType: signalType, toolName: toolName
+ sessionId: sessionId, signal: signal, toolName: toolName
)
- self?.scanner.scan()
+ self?.stateManager.refreshFromHookState()
}
hookServer.start()
scanner.start()
- logger.info("CodePulse launched — JSONL watcher + Notification/SessionStart/SessionEnd hooks active")
+ logger.info("CodePulse launched — hook-driven status detection (7 hooks) + JSONL supplementary data")
- // Clean up orphan CloudKit records from prior crashes or stale sessions
Task {
do {
let activeIds = Set(scanner.activeSessions.keys)
diff --git a/CodePulse-macOS/Services/ClaudeHookServer.swift b/CodePulse-macOS/Services/ClaudeHookServer.swift
index 11809f46..6b0be9e7 100644
--- a/CodePulse-macOS/Services/ClaudeHookServer.swift
+++ b/CodePulse-macOS/Services/ClaudeHookServer.swift
@@ -1,11 +1,13 @@
import Foundation
import Network
+import CodePulseShared
import os
private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "HookServer")
-/// Minimal hook server — only receives Notification events for instant permission detection.
-/// Uses a command hook (shell script) instead of HTTP hook to avoid blocking Claude Code.
+/// Hook-driven status detection server.
+/// Receives events from 7 Claude Code hooks via notify.sh command script.
+/// Hook events are the primary status source — JSONL parsing is supplementary.
final class ClaudeHookServer: @unchecked Sendable {
private var listener: NWListener?
private let port: UInt16
@@ -13,41 +15,85 @@ final class ClaudeHookServer: @unchecked Sendable {
private let lock = NSLock()
private var _permissionSessions: Set<String> = []
+ private var _stopSessions: Set<String> = []
+ private var _toolRunningSessions: Set<String> = []
- /// Sessions currently waiting for permission (thread-safe)
- var permissionSessions: Set<String> {
- lock.lock()
- defer { lock.unlock() }
- return _permissionSessions
- }
+ /// Maps cwd → most recently seen sessionId from hook events.
+ /// This is the authoritative source for "what sessionId is active for this project",
+ /// because hook events contain the REAL session_id (not the stale one in session files).
+ private var _cwdToSessionId: [String: String] = [:]
+
+ // MARK: - Thread-safe accessors
- /// Check if a specific session needs permission
func needsPermission(_ sessionId: String) -> Bool {
- lock.lock()
- defer { lock.unlock() }
- return _permissionSessions.contains(sessionId)
+ withLock { _permissionSessions.contains(sessionId) }
+ }
+
+ func isStopped(_ sessionId: String) -> Bool {
+ withLock { _stopSessions.contains(sessionId) }
+ }
+
+ func isToolRunning(_ sessionId: String) -> Bool {
+ withLock { _toolRunningSessions.contains(sessionId) }
}
- /// Clear permission state (called when JSONL shows activity resumed)
func clearPermission(_ sessionId: String) {
- lock.lock()
- _permissionSessions.remove(sessionId)
- lock.unlock()
+ withLock { _permissionSessions.remove(sessionId) }
+ }
+
+ func clearStop(_ sessionId: String) {
+ withLock { _stopSessions.remove(sessionId) }
}
- var onPermissionEvent: (@Sendable () -> Void)?
+ /// Remove all state for sessions no longer alive.
+ func pruneStale(activeSessionIds: Set<String>) {
+ withLock {
+ _permissionSessions.formIntersection(activeSessionIds)
+ _stopSessions.formIntersection(activeSessionIds)
+ _toolRunningSessions.formIntersection(activeSessionIds)
+ }
+ }
+
+ /// Get the real sessionId for a cwd, as reported by hook events.
+ /// Returns nil if no hook event has been received for this cwd yet.
+ func activeSessionId(forCwd cwd: String) -> String? {
+ withLock { _cwdToSessionId[cwd] }
+ }
+
+ // MARK: - Callbacks
+
+ var onHookSignal: (@Sendable (_ sessionId: String, _ signal: HookSignalType, _ toolName: String?) -> Void)?
var onSessionEvent: (@Sendable () -> Void)?
- /// Hook signal for TranscriptWatcher: (sessionId, signalType, toolName?)
- var onHookSignal: (@Sendable (_ sessionId: String, _ signalType: String, _ toolName: String?) -> Void)?
init(port: UInt16 = 19221) {
self.port = port
}
+ // MARK: - Lock helper
+
+ @discardableResult
+ private func withLock<T>(_ body: () -> T) -> T {
+ lock.lock()
+ defer { lock.unlock() }
+ return body()
+ }
+
+ /// Update all three state sets atomically for a session.
+ private func setSessionState(
+ _ sessionId: String,
+ permission: Bool? = nil,
+ stopped: Bool? = nil,
+ toolRunning: Bool? = nil
+ ) {
+ withLock {
+ if let p = permission { if p { _permissionSessions.insert(sessionId) } else { _permissionSessions.remove(sessionId) } }
+ if let s = stopped { if s { _stopSessions.insert(sessionId) } else { _stopSessions.remove(sessionId) } }
+ if let t = toolRunning { if t { _toolRunningSessions.insert(sessionId) } else { _toolRunningSessions.remove(sessionId) } }
+ }
+ }
+
// MARK: - Hook Configuration
- /// Install notify.sh and register a single Notification command hook.
- /// Also cleans up ALL old CodePulse HTTP hooks from settings.json.
func ensureHooksConfigured() {
installNotifyScript()
updateSettingsJson()
@@ -62,23 +108,17 @@ final class ClaudeHookServer: @unchecked Sendable {
let script = """
#!/bin/bash
- # CodePulse: non-blocking hook notification
- # Backgrounds curl so synchronous hooks (SessionStart) return instantly.
- # If CodePulse isn't running, curl fails silently — Claude Code is unaffected.
+ INPUT=$(cat)
curl -s --max-time 1 -X POST "http://127.0.0.1:\(port)/codepulse-event" \
-H "Content-Type: application/json" \
- -d "$HOOK_INPUT" 2>/dev/null &
+ -d "$INPUT" 2>/dev/null &
exit 0
"""
try? script.write(to: scriptPath, atomically: true, encoding: .utf8)
-
- // Make executable
var attrs = [FileAttributeKey: Any]()
attrs[.posixPermissions] = 0o755
try? FileManager.default.setAttributes(attrs, ofItemAtPath: scriptPath.path)
-
- logger.info("Installed notify.sh at \(scriptPath.path)")
}
private func updateSettingsJson() {
@@ -89,15 +129,12 @@ final class ClaudeHookServer: @unchecked Sendable {
guard FileManager.default.fileExists(atPath: settingsURL.path),
let data = try? Data(contentsOf: settingsURL),
- var root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
- logger.warning("Could not read ~/.claude/settings.json")
- return
- }
+ var root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
var hooks = root["hooks"] as? [String: Any] ?? [:]
var changed = false
- // 1. Remove ALL old CodePulse HTTP hooks from every event type
+ // Remove old CodePulse hooks
for event in hooks.keys {
guard var entries = hooks[event] as? [[String: Any]] else { continue }
let before = entries.count
@@ -114,11 +151,12 @@ final class ClaudeHookServer: @unchecked Sendable {
}
}
- // 2. Register command hooks for Notification, SessionStart, SessionEnd
+ // Register all 7 hooks
let commandHook: [String: Any] = ["type": "command", "command": scriptPath]
let hookEntry: [String: Any] = ["hooks": [commandHook]]
+ let hookEvents = ["Notification", "Stop", "UserPromptSubmit", "PreToolUse", "PostToolUse", "SessionStart", "SessionEnd"]
- for event in ["Notification", "SessionStart", "SessionEnd", "PermissionRequest", "PreCompact"] {
+ for event in hookEvents {
var entries = hooks[event] as? [[String: Any]] ?? []
let alreadyPresent = entries.contains { entry in
guard let entryHooks = entry["hooks"] as? [[String: Any]] else { return false }
@@ -135,12 +173,12 @@ final class ClaudeHookServer: @unchecked Sendable {
root["hooks"] = hooks
if let data = try? JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys]) {
try? data.write(to: settingsURL, options: .atomic)
- logger.info("Updated hooks in settings.json (Notification command hook only)")
+ logger.info("Updated hooks in settings.json (7 hook events)")
}
}
}
- // MARK: - Server (receives events from notify.sh)
+ // MARK: - Server
func start() {
do {
@@ -158,14 +196,10 @@ final class ClaudeHookServer: @unchecked Sendable {
listener?.stateUpdateHandler = { state in
if case .ready = state {
- logger.info("Notification hook server listening on port \(self.port)")
+ logger.info("Hook server listening on port \(self.port)")
}
}
-
- listener?.newConnectionHandler = { [weak self] connection in
- self?.handleConnection(connection)
- }
-
+ listener?.newConnectionHandler = { [weak self] conn in self?.handleConnection(conn) }
listener?.start(queue: queue)
}
@@ -178,17 +212,12 @@ final class ClaudeHookServer: @unchecked Sendable {
private func handleConnection(_ connection: NWConnection) {
connection.start(queue: queue)
-
var accumulated = Data()
func receiveMore() {
connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, isComplete, error in
if let data { accumulated.append(data) }
-
- if accumulated.count > 512_000 {
- connection.cancel()
- return
- }
+ if accumulated.count > 512_000 { connection.cancel(); return }
let done = isComplete || error != nil
let hasFullRequest = String(data: accumulated, encoding: .utf8)?.contains("\r\n\r\n") ?? false
@@ -220,6 +249,14 @@ final class ClaudeHookServer: @unchecked Sendable {
let eventName = json["hook_event_name"] as? String ?? ""
let sessionId = json["session_id"] as? String
let toolName = json["tool_name"] as? String
+ let cwd = json["cwd"] as? String
+
+ // Track cwd → sessionId mapping from every hook event.
+ // This is the only reliable way to know the real sessionId for a project,
+ // because session files record the initial ID which becomes stale after /resume.
+ if let sessionId, let cwd {
+ withLock { _cwdToSessionId[cwd] = sessionId }
+ }
switch eventName {
case "Notification":
@@ -227,57 +264,59 @@ final class ClaudeHookServer: @unchecked Sendable {
let notificationType = json["notification_type"] as? String
?? (json["message"] as? [String: Any])?["notification_type"] as? String
- switch notificationType {
- case "permission_prompt":
- lock.lock()
- _permissionSessions.insert(sessionId)
- lock.unlock()
- logger.debug("Permission needed for session \(sessionId.prefix(8))...")
- DispatchQueue.main.async { [weak self] in
- self?.onHookSignal?(sessionId, "permission_request", toolName)
- self?.onPermissionEvent?()
- }
- case "elicitation_dialog":
- DispatchQueue.main.async { [weak self] in
- self?.onHookSignal?(sessionId, "elicitation_dialog", nil)
- self?.onPermissionEvent?()
- }
- case "idle_prompt":
- DispatchQueue.main.async { [weak self] in
- self?.onHookSignal?(sessionId, "idle_prompt", nil)
- }
- default:
- break
+ if toolName == "AskUserQuestion" {
+ setSessionState(sessionId, permission: true, stopped: false, toolRunning: false)
+ emit(sessionId, .askUserQuestion, toolName)
+ } else if notificationType == "permission_prompt" {
+ setSessionState(sessionId, permission: true, stopped: false, toolRunning: false)
+ emit(sessionId, .permissionRequest, toolName)
+ } else if notificationType == "elicitation_dialog" {
+ setSessionState(sessionId, permission: true, stopped: false)
+ emit(sessionId, .elicitationDialog, nil)
}
- case "PermissionRequest":
+ case "Stop":
guard let sessionId else { return }
- lock.lock()
- _permissionSessions.insert(sessionId)
- lock.unlock()
- logger.debug("PermissionRequest for session \(sessionId.prefix(8))...")
- DispatchQueue.main.async { [weak self] in
- self?.onHookSignal?(sessionId, "permission_request", toolName)
- self?.onPermissionEvent?()
- }
+ setSessionState(sessionId, permission: false, stopped: true, toolRunning: false)
+ emit(sessionId, .stop, nil)
- case "PreCompact":
+ case "UserPromptSubmit":
guard let sessionId else { return }
- logger.debug("PreCompact for session \(sessionId.prefix(8))...")
- DispatchQueue.main.async { [weak self] in
- self?.onHookSignal?(sessionId, "pre_compact", nil)
- }
+ setSessionState(sessionId, permission: false, stopped: false, toolRunning: false)
+ emit(sessionId, .userPromptSubmit, nil)
+
+ case "PreToolUse":
+ guard let sessionId else { return }
+ setSessionState(sessionId, stopped: false, toolRunning: true)
+ emit(sessionId, .preToolUse, toolName)
+
+ case "PostToolUse":
+ guard let sessionId else { return }
+ setSessionState(sessionId, toolRunning: false)
+ emit(sessionId, .postToolUse, toolName)
case "SessionStart":
- logger.info("SessionStart hook fired\(sessionId.map { " for \($0.prefix(8))..." } ?? "")")
+ logger.info("SessionStart\(sessionId.map { " \($0.prefix(8))..." } ?? "")")
DispatchQueue.main.async { [weak self] in self?.onSessionEvent?() }
case "SessionEnd":
- logger.info("SessionEnd hook fired\(sessionId.map { " for \($0.prefix(8))..." } ?? "")")
+ guard let sessionId else {
+ DispatchQueue.main.async { [weak self] in self?.onSessionEvent?() }
+ return
+ }
+ setSessionState(sessionId, permission: false, stopped: false, toolRunning: false)
+ logger.info("SessionEnd \(sessionId.prefix(8))...")
DispatchQueue.main.async { [weak self] in self?.onSessionEvent?() }
default:
break
}
}
+
+ private func emit(_ sessionId: String, _ signal: HookSignalType, _ toolName: String?) {
+ DispatchQueue.main.async { [weak self] in
+ self?.onHookSignal?(sessionId, signal, toolName)
+ self?.onSessionEvent?()
+ }
+ }
}
diff --git a/CodePulse-macOS/Services/SessionFileParser.swift b/CodePulse-macOS/Services/SessionFileParser.swift
index a1cba5f3..951ce1b5 100644
--- a/CodePulse-macOS/Services/SessionFileParser.swift
+++ b/CodePulse-macOS/Services/SessionFileParser.swift
@@ -1,7 +1,7 @@
import Foundation
import CodePulseShared
-struct RawSessionFile: Codable {
+struct RawSessionFile: Codable, Equatable {
let pid: Int
let sessionId: String
let cwd: String
@@ -111,4 +111,13 @@ enum SessionFileParser {
let index = try? JSONDecoder().decode(SessionIndex.self, from: data) else { return nil }
return index.entries.first { $0.sessionId == sessionId }
}
+
+ /// Fall back to the latest entry in sessions-index.json for a project.
+ /// Used when the active sessionId (resolved from JSONL) differs from what's in the index.
+ static func parseLatestSessionIndex(cwd: String) -> SessionIndexEntry? {
+ let path = ClaudePaths.sessionIndexPath(cwd: cwd)
+ guard let data = try? Data(contentsOf: path),
+ let index = try? JSONDecoder().decode(SessionIndex.self, from: data) else { return nil }
+ return index.entries.last
+ }
}
diff --git a/CodePulse-macOS/Services/SessionScanner.swift b/CodePulse-macOS/Services/SessionScanner.swift
index 5831bf42..55b3b13e 100644
--- a/CodePulse-macOS/Services/SessionScanner.swift
+++ b/CodePulse-macOS/Services/SessionScanner.swift
@@ -8,6 +8,9 @@ private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "Session
final class SessionScanner: ObservableObject {
@Published var activeSessions: [String: RawSessionFile] = [:]
+ /// Reference to the hook server for cwd→sessionId resolution
+ var hookServer: ClaudeHookServer?
+
private var sessionsWatcher: DispatchSourceFileSystemObject?
private var scanTimer: Timer?
private let debounceInterval: TimeInterval = 1.0
@@ -32,7 +35,6 @@ final class SessionScanner: ObservableObject {
scanTimer?.invalidate()
scanTimer = nil
debounceTask?.cancel()
- logger.info("SessionScanner stopped")
}
private func scheduleScan() {
@@ -44,17 +46,100 @@ final class SessionScanner: ObservableObject {
}
}
+ /// Called from hook events — uses the same debounce to avoid redundant scans.
+ func scheduleScanFromHook() {
+ scheduleScan()
+ }
+
func scan() {
let files = SessionFileParser.parseSessionFiles()
var newSessions: [String: RawSessionFile] = [:]
+
for file in files {
guard PIDChecker.isAlive(pid: file.pid) else { continue }
- newSessions[file.sessionId] = file
+
+ // Resolution priority:
+ // 1. Hook server knows the real sessionId (from hook events with cwd)
+ // 2. Fall back to JSONL directory scan (single-session projects only)
+ // 3. Use the session file's original sessionId
+ let resolved = resolveSessionId(file)
+ newSessions[resolved.sessionId] = resolved
+ }
+
+ if newSessions != activeSessions {
+ if newSessions.count != activeSessions.count {
+ logger.info("Active sessions: \(newSessions.count)")
+ }
+ activeSessions = newSessions
}
- if newSessions.count != activeSessions.count {
- logger.info("Active sessions: \(newSessions.count)")
+ }
+
+ /// Resolve the real sessionId for a session file.
+ /// Hook events provide the authoritative mapping (cwd → sessionId).
+ /// Falls back to JSONL directory scan when no hook data is available.
+ private func resolveSessionId(_ file: RawSessionFile) -> RawSessionFile {
+ // 1. Ask hook server — it has the real sessionId from live events
+ if let hookSessionId = hookServer?.activeSessionId(forCwd: file.cwd),
+ hookSessionId != file.sessionId {
+ return RawSessionFile(pid: file.pid, sessionId: hookSessionId, cwd: file.cwd, startedAt: file.startedAt)
}
- activeSessions = newSessions
+
+ // 2. Check if original JSONL exists — if so, no resolution needed
+ let originalJsonl = ClaudePaths.jsonlPath(cwd: file.cwd, sessionId: file.sessionId)
+ if FileManager.default.fileExists(atPath: originalJsonl.path) {
+ return file
+ }
+
+ // 3. Fall back to finding the most recently modified JSONL in the project directory
+ return resolveFromJsonlDirectory(file)
+ }
+
+ /// Last-resort: scan the project directory for the most recently modified JSONL.
+ /// Used when no hook data is available and the original JSONL doesn't exist.
+ private func resolveFromJsonlDirectory(_ file: RawSessionFile) -> RawSessionFile {
+ let projectDir = ClaudePaths.projectsDir
+ .appendingPathComponent(ClaudePaths.mangledCwd(file.cwd))
+
+ guard let contents = try? FileManager.default.contentsOfDirectory(
+ at: projectDir, includingPropertiesForKeys: [.contentModificationDateKey]
+ ) else {
+ return file
+ }
+
+ let jsonlFiles = contents.filter { url in
+ url.pathExtension == "jsonl"
+ && !url.lastPathComponent.hasPrefix("agent-")
+ }
+
+ var bestURL: URL?
+ var bestDate: Date = .distantPast
+ for url in jsonlFiles {
+ guard let values = try? url.resourceValues(forKeys: [.contentModificationDateKey]),
+ let modDate = values.contentModificationDate else { continue }
+ if modDate > bestDate {
+ bestDate = modDate
+ bestURL = url
+ }
+ }
+
+ guard let activeURL = bestURL else { return file }
+ let activeSessionId = activeURL.deletingPathExtension().lastPathComponent
+
+ // Only resolve if the best JSONL was modified recently (within 2 minutes)
+ let age = Date().timeIntervalSince(bestDate)
+ guard age < 120 else { return file }
+
+ if activeSessionId != file.sessionId {
+ logger.info("Session PID=\(file.pid): resolved \(file.sessionId.prefix(8))→\(activeSessionId.prefix(8)) (active JSONL)")
+ return RawSessionFile(
+ pid: file.pid,
+ sessionId: activeSessionId,
+ cwd: file.cwd,
+ startedAt: file.startedAt
+ )
+ }
+
+ return file
}
private func watchDirectory(_ url: URL, handler: @escaping () -> Void) {
diff --git a/CodePulse-macOS/Services/SessionStateManager.swift b/CodePulse-macOS/Services/SessionStateManager.swift
index c6ee4947..2443fa44 100644
--- a/CodePulse-macOS/Services/SessionStateManager.swift
+++ b/CodePulse-macOS/Services/SessionStateManager.swift
@@ -26,26 +26,40 @@ final class SessionStateManager: ObservableObject {
.store(in: &cancellables)
}
+ /// Force a status re-evaluation.
+ /// Called when hook state changes (Stop, Permission, etc.).
+ /// Re-scans first so sessionIds are resolved with latest hook data,
+ /// then runs updateSessions even if the session list looks the same.
+ func refreshFromHookState() {
+ scanner.scan()
+ updateSessions(from: scanner.activeSessions)
+ }
+
private func updateSessions(from rawSessions: [String: RawSessionFile]) {
var updated: [SessionState] = []
for (sessionId, raw) in rawSessions {
- // Parse JSONL incrementally — this is now the primary state source
+ // Parse JSONL incrementally — supplementary data (model, tokens, cost, lastEvent)
let jsonlUrl = ClaudePaths.jsonlPath(cwd: raw.cwd, sessionId: sessionId)
transcriptWatcher.update(sessionId: sessionId, jsonlURL: jsonlUrl)
let transcript = transcriptWatcher.state(for: sessionId)
let tasks = SessionFileParser.parseTasks(sessionId: sessionId)
+ // Try exact sessionId first, then fall back to latest entry for this project
+ // (handles resolved sessions where sessionId differs from index)
let indexEntry = SessionFileParser.parseSessionIndex(cwd: raw.cwd, sessionId: sessionId)
+ ?? SessionFileParser.parseLatestSessionIndex(cwd: raw.cwd)
- // Permission: instant detection from hook, clear when transcript shows activity
+ // Hook-driven: clear stale hook states when transcript shows activity resumed
let needsPermission = hookServer?.needsPermission(sessionId) ?? false
if needsPermission, let t = transcript, t.status == .working {
- // JSONL shows activity resumed — clear permission flag
hookServer?.clearPermission(sessionId)
}
+ if hookServer?.isStopped(sessionId) == true, let t = transcript, t.status == .working {
+ hookServer?.clearStop(sessionId)
+ }
- let status = detectStatus(
+ let (status, waitingReason) = detectStatus(
raw: raw,
transcript: transcript,
tasks: tasks,
@@ -58,29 +72,35 @@ final class SessionStateManager: ObservableObject {
let currentTask = tasks.first(where: { $0.status == .inProgress })?.activeForm
let lastEvent = transcript?.lastEvent
- let summary = indexEntry?.summary
- ?? indexEntry?.firstPrompt.map { String($0.prefix(50)) }
- ?? projectName
+ // Summary priority: sessions-index summary > lastPrompt > firstPrompt > project name
+ // Filter out system messages like "[Request interrupted by user]"
+ let isUsable = { (s: String) -> Bool in
+ !s.isEmpty && !s.hasPrefix("[Request") && !s.hasPrefix("[Error")
+ }
+ let summary: String = {
+ if let s = indexEntry?.summary, isUsable(s) { return s }
+ if let lp = transcript?.lastPrompt, isUsable(lp) { return lp }
+ if let fp = transcript?.firstPrompt, isUsable(fp) { return fp }
+ if let fp = indexEntry?.firstPrompt, isUsable(fp) { return String(fp.prefix(80)) }
+ return projectName
+ }()
- let existingSession = sessions.first { $0.sessionId == sessionId }
- let contentChanged = existingSession == nil
- || existingSession?.status != status
- || existingSession?.tasks != tasks
- || existingSession?.contextPct != (transcript?.contextPct ?? 0)
- || existingSession?.currentTask != currentTask
- || existingSession?.lastEvent != lastEvent
+ // Git branch: sessions-index > direct git query > "unknown"
+ let gitBranch = indexEntry?.gitBranch ?? Self.gitBranch(cwd: raw.cwd)
- let updatedAt = contentChanged ? Date() : (existingSession?.updatedAt ?? Date())
+ let existingSession = sessions.first { $0.sessionId == sessionId }
+ let updatedAt = transcript?.lastActivityTime ?? existingSession?.updatedAt ?? startDate
let session = SessionState(
sessionId: sessionId,
projectName: projectName,
- gitBranch: indexEntry?.gitBranch ?? "unknown",
+ gitBranch: gitBranch,
status: status,
model: formatModel(transcript?.model ?? "Unknown"),
summary: summary,
currentTask: currentTask,
lastEvent: lastEvent,
+ waitingReason: waitingReason,
tasks: tasks,
contextPct: transcript?.contextPct ?? 0,
costUSD: transcript?.costUSD ?? 0,
@@ -97,6 +117,7 @@ final class SessionStateManager: ObservableObject {
if !rawSessions.keys.contains(existing.sessionId) {
var completed = existing
completed.status = .completed
+ completed.waitingReason = nil
completed.updatedAt = Date()
updated.append(completed)
transcriptWatcher.removeSession(existing.sessionId)
@@ -109,43 +130,112 @@ final class SessionStateManager: ObservableObject {
}
}
+ private var skipPermissionsCache: [Int: Bool] = [:]
+
+ private func isSkipPermissions(pid: Int) -> Bool {
+ if let cached = skipPermissionsCache[pid] { return cached }
+ let result = PIDChecker.skipsPermissions(pid: pid)
+ skipPermissionsCache[pid] = result
+ return result
+ }
+
+ /// Hook-driven status detection.
+ /// Priority: PID check → Stop hook → Permission hook → Tool running hook → Transcript → Tasks → Idle
private func detectStatus(
raw: RawSessionFile,
transcript: TranscriptState?,
tasks: [TaskItem],
needsPermission: Bool
- ) -> SessionStatus {
+ ) -> (SessionStatus, WaitingReason?) {
// 1. PID dead → completed
- guard PIDChecker.isAlive(pid: raw.pid) else { return .completed }
+ guard PIDChecker.isAlive(pid: raw.pid) else {
+ skipPermissionsCache.removeValue(forKey: raw.pid)
+ return (.completed, nil)
+ }
+
+ let bypassed = isSkipPermissions(pid: raw.pid)
+ let sessionId = raw.sessionId
- // 2. Hook says needs permission (instant, from Notification hook)
- if needsPermission { return .needsInput }
+ // 2. Hook: Stop fired → waiting for user input (yellow)
+ if hookServer?.isStopped(sessionId) == true {
+ return (.needsInput, .commandComplete)
+ }
+
+ // 3. Hook: Permission/elicitation/askUserQuestion needed (red or yellow)
+ if needsPermission && !bypassed {
+ let reason: WaitingReason
+ if let lastEvent = transcript?.lastEvent {
+ if lastEvent.contains("Waiting for input") {
+ reason = .askUserQuestion
+ } else {
+ reason = .permissionPrompt
+ }
+ } else {
+ reason = .permissionPrompt
+ }
+ return (.needsInput, reason)
+ }
+
+ // 4. Hook: Tool currently running → working
+ if hookServer?.isToolRunning(sessionId) == true {
+ return (.working, nil)
+ }
- // 3. Transcript state (from JSONL parsing)
+ // 5. Transcript state (supplementary — for working/compacting/idle)
if let transcript {
switch transcript.status {
case .working:
- return .working
+ return (.working, nil)
case .waitingForUser:
- return .needsInput
+ return (bypassed ? .idle : .needsInput, bypassed ? nil : .unknown)
case .compacting:
- return .compacting
+ return (.compacting, nil)
case .idle:
- return .idle
+ return (.idle, nil)
}
}
- // 4. Fallback: check tasks
- if tasks.contains(where: { $0.status == .inProgress }) { return .working }
+ // 6. Fallback: check tasks
+ if tasks.contains(where: { $0.status == .inProgress }) { return (.working, nil) }
- // 5. No signal → idle
- return .idle
+ // 7. No signal → idle
+ return (.idle, nil)
+ }
+
+ private static var gitBranchCache: [String: (branch: String, time: Date)] = [:]
+
+ private static func gitBranch(cwd: String) -> String {
+ // Cache for 30 seconds to avoid spawning git on every scan
+ if let cached = gitBranchCache[cwd],
+ Date().timeIntervalSince(cached.time) < 30 {
+ return cached.branch
+ }
+ let proc = Process()
+ proc.executableURL = URL(fileURLWithPath: "/usr/bin/git")
+ proc.arguments = ["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"]
+ proc.currentDirectoryURL = URL(fileURLWithPath: cwd)
+ let pipe = Pipe()
+ proc.standardOutput = pipe
+ proc.standardError = FileHandle.nullDevice
+ do {
+ try proc.run()
+ proc.waitUntilExit()
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ let branch = String(data: data, encoding: .utf8)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ let result = branch.isEmpty ? "unknown" : branch
+ gitBranchCache[cwd] = (result, Date())
+ return result
+ } catch {
+ return "unknown"
+ }
}
private func formatModel(_ raw: String) -> String {
if raw.contains("opus") { return "Opus" }
if raw.contains("sonnet") { return "Sonnet" }
if raw.contains("haiku") { return "Haiku" }
+ if raw == "Unknown" || raw.contains("synthetic") { return "" }
return raw
}
}
diff --git a/CodePulse-macOS/Services/TranscriptWatcher.swift b/CodePulse-macOS/Services/TranscriptWatcher.swift
index 18d0d09c..8eb85750 100644
--- a/CodePulse-macOS/Services/TranscriptWatcher.swift
+++ b/CodePulse-macOS/Services/TranscriptWatcher.swift
@@ -1,4 +1,5 @@
import Foundation
+import CodePulseShared
import os
private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "TranscriptWatcher")
@@ -13,6 +14,8 @@ struct TranscriptState: Sendable {
var latestInputTokens: Int = 0
var totalOutputTokens: Int = 0
var lastActivityTime: Date = Date()
+ var firstPrompt: String = ""
+ var lastPrompt: String = ""
var contextPct: Int {
guard latestInputTokens > 0 else { return 0 }
@@ -58,46 +61,69 @@ final class TranscriptWatcher {
// Compaction state: when true, suppress replayed user/progress messages
var isCompacting: Bool = false
+
+ // Whether this session has received at least one hook event.
+ // Sessions that started before hooks were registered need JSONL-based
+ // permission timeout as a fallback.
+ var hasReceivedHookEvent: Bool = false
}
private var trackers: [String: SessionTracker] = [:]
private let decoder = JSONDecoder()
- /// Permission timeout — tool started but no result
- private let permissionTimeoutSeconds: TimeInterval = 8.0
-
// MARK: - Public API
func state(for sessionId: String) -> TranscriptState? {
trackers[sessionId]?.state
}
- /// Receive a hook signal (permission, idle, compact) from ClaudeHookServer
- func handleHookSignal(sessionId: String, signalType: String, toolName: String? = nil) {
- guard var tracker = trackers[sessionId] else { return }
+ /// Receive a hook signal from ClaudeHookServer.
+ /// Hook signals are the primary status source — they override JSONL-derived state.
+ func handleHookSignal(sessionId: String, signal: HookSignalType, toolName: String? = nil) {
+ guard var tracker = trackers[sessionId] else {
+ var newTracker = SessionTracker()
+ newTracker.state.lastActivityTime = Date()
+ applyHookSignal(signal, toolName: toolName, tracker: &newTracker)
+ trackers[sessionId] = newTracker
+ return
+ }
tracker.state.lastActivityTime = Date()
+ applyHookSignal(signal, toolName: toolName, tracker: &tracker)
+ trackers[sessionId] = tracker
+ }
- switch signalType {
- case "permission_request":
+ private func applyHookSignal(_ signal: HookSignalType, toolName: String?, tracker: inout SessionTracker) {
+ tracker.hasReceivedHookEvent = true
+ switch signal {
+ case .permissionRequest:
tracker.state.status = .waitingForUser
tracker.state.lastEvent = toolName.map { "Permission: \($0)" } ?? "Needs permission"
- case "elicitation_dialog":
+ case .askUserQuestion:
tracker.state.status = .waitingForUser
tracker.state.lastEvent = "Waiting for input"
- case "idle_prompt":
- if tracker.activeAgents.isEmpty {
- tracker.state.status = .idle
- tracker.state.lastEvent = ""
+ case .elicitationDialog:
+ tracker.state.status = .waitingForUser
+ tracker.state.lastEvent = "Waiting for input"
+ case .stop:
+ tracker.state.status = .idle
+ tracker.state.lastEvent = ""
+ tracker.activeToolIds.removeAll()
+ tracker.activeAgents.removeAll()
+ tracker.lastToolStartTime = nil
+ case .userPromptSubmit:
+ tracker.state.status = .working
+ tracker.state.lastEvent = "Processing prompt..."
+ tracker.activeToolIds.removeAll()
+ tracker.activeAgents.removeAll()
+ tracker.lastToolStartTime = nil
+ case .preToolUse:
+ tracker.state.status = .working
+ if let toolName {
+ tracker.state.lastEvent = formatToolStatus(name: toolName, input: nil)
}
- case "pre_compact":
- tracker.state.status = .compacting
- tracker.state.lastEvent = "Compacting context..."
- tracker.isCompacting = true
- default:
+ case .postToolUse:
break
}
-
- trackers[sessionId] = tracker
}
/// Process new data from a session's JSONL file. Call this on each scan cycle.
@@ -182,6 +208,10 @@ final class TranscriptWatcher {
processSystem(entry, tracker: &tracker)
case "progress":
processProgress(entry, tracker: &tracker)
+ case "last-prompt":
+ if let prompt = entry.lastPrompt, !prompt.isEmpty {
+ tracker.state.lastPrompt = String(prompt.prefix(100))
+ }
default:
break
}
@@ -304,6 +334,17 @@ final class TranscriptWatcher {
tracker.activeToolIds.removeAll()
tracker.activeAgents.removeAll()
tracker.lastToolStartTime = nil
+
+ // Extract prompt text for summary
+ if let textBlock = content.first(where: { $0.type == "text" }),
+ let text = textBlock.text?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !text.isEmpty, !text.hasPrefix("<") {
+ let clean = String(text.prefix(100))
+ tracker.state.lastPrompt = clean
+ if tracker.state.firstPrompt.isEmpty {
+ tracker.state.firstPrompt = clean
+ }
+ }
} else {
// User message without promptId and without tool_result — likely still working
tracker.state.status = .working
@@ -364,22 +405,25 @@ final class TranscriptWatcher {
let now = Date()
let sinceLastActivity = now.timeIntervalSince(tracker.state.lastActivityTime)
- // Permission heuristic: tool started but no result after timeout
- if !tracker.activeToolIds.isEmpty,
- tracker.activeAgents.isEmpty, // Don't timeout on subagents
+ // For sessions that started BEFORE hooks were registered (e.g., app just installed),
+ // use JSONL-based permission timeout as fallback. Once any hook fires, this is disabled.
+ if !tracker.hasReceivedHookEvent,
+ !tracker.activeToolIds.isEmpty,
+ tracker.activeAgents.isEmpty,
let toolStart = tracker.lastToolStartTime,
- now.timeIntervalSince(toolStart) > permissionTimeoutSeconds {
+ now.timeIntervalSince(toolStart) > 8.0 {
if tracker.state.status == .working {
tracker.state.status = .waitingForUser
tracker.state.lastEvent = "Needs permission"
}
}
- // Working with no tools and no new data → likely idle
+ // Safety net: if working with no activity for 30s and no active tools, assume idle.
+ // Normally Stop hook handles this instantly — this catches edge cases only.
if tracker.state.status == .working,
tracker.activeToolIds.isEmpty,
tracker.activeAgents.isEmpty,
- sinceLastActivity > 15.0 {
+ sinceLastActivity > 30.0 {
tracker.state.status = .idle
tracker.state.lastEvent = ""
}
diff --git a/CodePulse-macOS/Utilities/JSONLTailReader.swift b/CodePulse-macOS/Utilities/JSONLTailReader.swift
index 99723d22..144990b6 100644
--- a/CodePulse-macOS/Utilities/JSONLTailReader.swift
+++ b/CodePulse-macOS/Utilities/JSONLTailReader.swift
@@ -82,6 +82,8 @@ struct JSONLTranscriptEntry: Codable {
let agentId: String?
let promptId: String?
let data: JSONLProgressData?
+ /// Present on "last-prompt" type entries
+ let lastPrompt: String?
}
struct JSONLSessionInfo {
diff --git a/CodePulse-macOS/Utilities/PIDChecker.swift b/CodePulse-macOS/Utilities/PIDChecker.swift
index 98f017f3..b244687f 100644
--- a/CodePulse-macOS/Utilities/PIDChecker.swift
+++ b/CodePulse-macOS/Utilities/PIDChecker.swift
@@ -4,4 +4,23 @@ enum PIDChecker {
static func isAlive(pid: Int) -> Bool {
kill(Int32(pid), 0) == 0
}
+
+ /// Check if a process was launched with --dangerously-skip-permissions
+ static func skipsPermissions(pid: Int) -> Bool {
+ let proc = Process()
+ proc.executableURL = URL(fileURLWithPath: "/bin/ps")
+ proc.arguments = ["-p", "\(pid)", "-o", "args="]
+ let pipe = Pipe()
+ proc.standardOutput = pipe
+ proc.standardError = FileHandle.nullDevice
+ do {
+ try proc.run()
+ proc.waitUntilExit()
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ let args = String(data: data, encoding: .utf8) ?? ""
+ return args.contains("--dangerously-skip-permissions")
+ } catch {
+ return false
+ }
+ }
}
diff --git a/CodePulse-macOS/Views/SessionDetailView.swift b/CodePulse-macOS/Views/SessionDetailView.swift
index f45d2d80..1c920237 100644
--- a/CodePulse-macOS/Views/SessionDetailView.swift
+++ b/CodePulse-macOS/Views/SessionDetailView.swift
@@ -29,11 +29,12 @@ struct SessionDetailView: View {
SessionStatusView(
status: session.status,
completedTasks: session.completedTaskCount,
- totalTasks: session.totalTaskCount
+ totalTasks: session.totalTaskCount,
+ waitingReason: session.waitingReason
)
- Text(session.status.label)
+ Text(statusLabel)
.font(.system(size: 11, weight: .medium))
- .foregroundStyle(session.status == .needsInput ? theme.warning : theme.secondaryText)
+ .foregroundStyle(statusLabelColor)
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
@@ -44,23 +45,24 @@ struct SessionDetailView: View {
VStack(alignment: .leading, spacing: 12) {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 4) {
- Text(session.summary)
+ Text(session.projectName)
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(theme.primaryText)
- .lineLimit(2)
if !session.model.isEmpty {
SessionTagView(tag: session.model)
}
}
+ if session.summary != session.projectName {
+ Text(session.summary)
+ .font(.system(size: 12))
+ .foregroundStyle(theme.secondaryText)
+ .lineLimit(2)
+ }
HStack(spacing: 6) {
- Label(session.projectName, systemImage: "folder")
- if !session.gitBranch.isEmpty {
- Text("·")
- Text(session.gitBranch)
- }
+ Label(session.gitBranch.isEmpty ? session.projectName : session.gitBranch, systemImage: "arrow.triangle.branch")
}
.font(.system(size: 11))
- .foregroundStyle(theme.secondaryText)
+ .foregroundStyle(theme.tertiaryText)
}
HStack(spacing: 0) {
@@ -110,15 +112,25 @@ struct SessionDetailView: View {
}
}
+ private var statusLabel: String {
+ guard session.status == .needsInput else { return session.status.label }
+ return session.waitingReason?.label ?? "Needs Input"
+ }
+
+ private var statusLabelColor: Color {
+ guard session.status == .needsInput else { return theme.secondaryText }
+ return theme.waitingColor(for: session.waitingReason)
+ }
+
private func taskIcon(_ status: TaskStatus) -> some View {
Group {
switch status {
case .completed:
- Image(systemName: "checkmark.circle.fill").foregroundStyle(.blue)
+ Image(systemName: "checkmark.circle.fill").foregroundStyle(theme.primaryText.opacity(0.7))
case .inProgress:
- Image(systemName: "circlebadge.fill").foregroundStyle(.blue)
+ Image(systemName: "circlebadge.fill").foregroundStyle(theme.primaryText.opacity(0.7))
case .pending:
- Image(systemName: "circle").foregroundStyle(theme.secondaryText)
+ Image(systemName: "circle").foregroundStyle(theme.tertiaryText)
}
}
.font(.system(size: 11))
@@ -127,11 +139,11 @@ struct SessionDetailView: View {
private func statItem(_ value: String, _ label: String) -> some View {
VStack(spacing: 2) {
Text(value)
- .font(.system(size: 13, weight: .semibold, design: .rounded))
+ .font(.system(size: 13, weight: .semibold, design: .monospaced))
.foregroundStyle(theme.primaryText)
Text(label)
.font(.system(size: 10))
- .foregroundStyle(theme.secondaryText)
+ .foregroundStyle(theme.tertiaryText)
}
.frame(maxWidth: .infinity)
}
@@ -148,6 +160,7 @@ struct SessionDetailView: View {
private struct DetailProgressRing: View {
let completed: Int
let total: Int
+ @Environment(\.theme) private var theme
@State private var animatedProgress: Double = 0
private var progress: Double {
@@ -156,14 +169,14 @@ private struct DetailProgressRing: View {
var body: some View {
ZStack {
- Circle().stroke(Color.primary.opacity(0.06), lineWidth: 3)
+ Circle().stroke(theme.secondaryText.opacity(0.15), lineWidth: 3)
Circle()
.trim(from: 0, to: animatedProgress)
- .stroke(Color.blue, style: StrokeStyle(lineWidth: 3, lineCap: .round))
+ .stroke(theme.primaryText.opacity(0.7), style: StrokeStyle(lineWidth: 3, lineCap: .round))
.rotationEffect(.degrees(-90))
Text("\(Int(progress * 100))%")
- .font(.system(size: 10, weight: .semibold, design: .rounded))
- .foregroundStyle(.primary)
+ .font(.system(size: 10, weight: .semibold, design: .monospaced))
+ .foregroundStyle(theme.primaryText)
}
.frame(width: 36, height: 36)
.onAppear { withAnimation(.easeOut(duration: 0.6)) { animatedProgress = progress } }
diff --git a/CodePulse-macOS/Views/SessionListView.swift b/CodePulse-macOS/Views/SessionListView.swift
index d5db1fd8..0aa181a7 100644
--- a/CodePulse-macOS/Views/SessionListView.swift
+++ b/CodePulse-macOS/Views/SessionListView.swift
@@ -8,7 +8,6 @@ struct SessionListView: View {
@Environment(\.theme) private var injectedTheme
private var theme: CodePulseTheme {
- // If a notch theme is injected from the panel, use it; otherwise derive from user preference
injectedTheme.isPanel ? injectedTheme : CodePulseTheme(isDark: isDarkMode)
}
@@ -49,7 +48,9 @@ struct SessionListView: View {
.frame(maxHeight: 420)
}
- Divider().padding(.horizontal, 8)
+ Divider()
+ .opacity(theme.isPanel ? 0.3 : 1)
+ .padding(.horizontal, 8)
footer
}
@@ -72,16 +73,18 @@ struct SessionListView: View {
HStack(alignment: .center, spacing: 8) {
Text("CodePulse")
.font(.system(size: 10, weight: .medium))
- .foregroundStyle(theme.secondaryText.opacity(0.6))
+ .foregroundStyle(theme.tertiaryText)
Spacer()
- Button(action: { isDarkMode.toggle() }) {
- Image(systemName: isDarkMode ? "sun.max" : "moon")
- .font(.system(size: 11))
- .foregroundStyle(theme.secondaryText)
+ if !theme.isPanel {
+ Button(action: { isDarkMode.toggle() }) {
+ Image(systemName: isDarkMode ? "sun.max" : "moon")
+ .font(.system(size: 11))
+ .foregroundStyle(theme.secondaryText)
+ }
+ .buttonStyle(.plain)
}
- .buttonStyle(.plain)
Button(action: { NSApp.terminate(nil) }) {
Text("Quit")
diff --git a/CodePulse-macOS/Views/SessionRowView.swift b/CodePulse-macOS/Views/SessionRowView.swift
index ac0f35b3..e9bfae27 100644
--- a/CodePulse-macOS/Views/SessionRowView.swift
+++ b/CodePulse-macOS/Views/SessionRowView.swift
@@ -8,6 +8,15 @@ struct SessionRowView: View {
@State private var isHovered = false
@State private var isPressed = false
+ /// Status description: summary (lastPrompt/firstPrompt) or lastEvent
+ private var statusDescription: String? {
+ if session.status == .working, let event = session.lastEvent, !event.isEmpty {
+ return event
+ }
+ let desc = session.summary
+ return desc != session.projectName ? desc : nil
+ }
+
var body: some View {
Button(action: {
withAnimation(.spring(duration: 0.15)) { isPressed = true }
@@ -20,41 +29,41 @@ struct SessionRowView: View {
SessionStatusView(
status: session.status,
completedTasks: session.completedTaskCount,
- totalTasks: session.totalTaskCount
+ totalTasks: session.totalTaskCount,
+ waitingReason: session.waitingReason
)
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 4) {
- Text(session.summary)
+ Text(session.projectName)
.font(.system(size: 13, weight: isHovered ? .medium : .regular))
.foregroundStyle(theme.primaryText)
.lineLimit(1)
- .truncationMode(.middle)
if !session.model.isEmpty {
SessionTagView(tag: session.model)
}
}
- if let subtitle = session.lastEvent ?? session.currentTask {
- Text(subtitle)
+ if let desc = statusDescription {
+ Text(desc)
.font(.system(size: 11))
- .foregroundStyle(session.status == .needsInput ? theme.warning : theme.secondaryText)
+ .foregroundStyle(subtitleColor)
.lineLimit(1)
}
}
Spacer(minLength: 4)
- Text(relativeTime(session.startedAt))
- .font(.system(size: 11, design: .rounded))
- .foregroundStyle(theme.secondaryText)
+ Text(relativeTime(session.updatedAt))
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundStyle(theme.tertiaryText)
}
.padding(.leading, 6)
.padding(.trailing, 10)
.padding(.vertical, 5)
.background(
RoundedRectangle(cornerRadius: 5, style: .continuous)
- .fill(isPressed ? theme.primaryText.opacity(0.1)
- : isHovered ? theme.primaryText.opacity(0.06)
+ .fill(isPressed ? theme.pressedBackground
+ : isHovered ? theme.hoverBackground
: Color.clear)
)
.scaleEffect(isPressed ? 0.98 : 1.0)
@@ -67,12 +76,17 @@ struct SessionRowView: View {
}
}
+ private var subtitleColor: Color {
+ guard session.status == .needsInput else { return theme.secondaryText }
+ return theme.waitingColor(for: session.waitingReason)
+ }
+
private func relativeTime(_ date: Date) -> String {
let seconds = -date.timeIntervalSinceNow
if seconds < 60 { return "now" }
- if seconds < 3600 { return "\(Int(seconds / 60))m ago" }
- if seconds < 86400 { return "\(Int(seconds / 3600))h ago" }
- if seconds < 604800 { return "\(Int(seconds / 86400))d ago" }
- return "\(Int(seconds / 604800))w ago"
+ if seconds < 3600 { return "\(Int(seconds / 60))m" }
+ if seconds < 86400 { return "\(Int(seconds / 3600))h" }
+ if seconds < 604800 { return "\(Int(seconds / 86400))d" }
+ return "\(Int(seconds / 604800))w"
}
}
diff --git a/CodePulse-macOS/Views/SessionTagView.swift b/CodePulse-macOS/Views/SessionTagView.swift
index e23c1f78..9038bb9c 100644
--- a/CodePulse-macOS/Views/SessionTagView.swift
+++ b/CodePulse-macOS/Views/SessionTagView.swift
@@ -2,16 +2,17 @@ import SwiftUI
struct SessionTagView: View {
let tag: String
+ @Environment(\.theme) private var theme
var body: some View {
Text(tag)
.font(.system(size: 9, weight: .medium, design: .monospaced))
- .foregroundStyle(.secondary)
- .padding(.horizontal, 3)
+ .foregroundStyle(theme.tertiaryText)
+ .padding(.horizontal, 4)
.padding(.vertical, 1)
.background(
RoundedRectangle(cornerRadius: 3, style: .continuous)
- .fill(Color.primary.opacity(0.06))
+ .fill(theme.border)
)
}
}
diff --git a/CodePulse-macOS/Views/StatusDotView.swift b/CodePulse-macOS/Views/StatusDotView.swift
index 843893cc..c7b0ca40 100644
--- a/CodePulse-macOS/Views/StatusDotView.swift
+++ b/CodePulse-macOS/Views/StatusDotView.swift
@@ -5,6 +5,7 @@ struct SessionStatusView: View {
let status: SessionStatus
let completedTasks: Int
let totalTasks: Int
+ var waitingReason: WaitingReason?
private var hasTasks: Bool { totalTasks > 0 }
private var progress: Double {
@@ -13,20 +14,24 @@ struct SessionStatusView: View {
var body: some View {
if hasTasks {
- ProgressRingView(progress: progress, status: status)
+ ProgressRingView(progress: progress, status: status, waitingReason: waitingReason)
.frame(width: 18, height: 18)
} else if status == .working {
ClaudeSparkleView()
.frame(width: 14, height: 14)
} else {
- MinimalDotView(status: status)
+ MinimalDotView(status: status, waitingReason: waitingReason)
}
}
}
+// MARK: - Progress Ring
+
private struct ProgressRingView: View {
let progress: Double
let status: SessionStatus
+ var waitingReason: WaitingReason?
+ @Environment(\.theme) private var theme
@State private var isPulsing = false
private var isWorking: Bool { status == .working }
@@ -35,22 +40,22 @@ private struct ProgressRingView: View {
var body: some View {
ZStack {
Circle()
- .stroke(Color.primary.opacity(0.08), lineWidth: 2)
+ .stroke(theme.secondaryText.opacity(0.15), lineWidth: 2)
Circle()
.trim(from: 0, to: progress)
- .stroke(Color.blue, style: StrokeStyle(lineWidth: 2, lineCap: .round))
+ .stroke(theme.primaryText.opacity(0.7), style: StrokeStyle(lineWidth: 2, lineCap: .round))
.rotationEffect(.degrees(-90))
if isWorking {
Circle()
.trim(from: max(0, progress - 0.08), to: progress)
- .stroke(Color.blue.opacity(0.6), style: StrokeStyle(lineWidth: 3, lineCap: .round))
+ .stroke(theme.primaryText.opacity(0.4), style: StrokeStyle(lineWidth: 3, lineCap: .round))
.rotationEffect(.degrees(-90))
.blur(radius: 1.5)
.opacity(isPulsing ? 1.0 : 0.3)
}
if needsAttention {
Circle()
- .fill(Color.orange)
+ .fill(attentionColor)
.frame(width: 5, height: 5)
.offset(x: 6, y: -6)
}
@@ -62,10 +67,18 @@ private struct ProgressRingView: View {
.onAppear { if isWorking { isPulsing = true } }
.onChange(of: status) { _, _ in isPulsing = (status == .working) }
}
+
+ private var attentionColor: Color {
+ theme.waitingColor(for: waitingReason)
+ }
}
+// MARK: - Minimal Dot
+
private struct MinimalDotView: View {
let status: SessionStatus
+ var waitingReason: WaitingReason?
+ @Environment(\.theme) private var theme
@State private var isPulsing = false
private var needsPulse: Bool { status == .needsInput || status == .error }
@@ -74,7 +87,7 @@ private struct MinimalDotView: View {
ZStack {
if needsPulse {
Circle()
- .fill(Color.orange.opacity(0.3))
+ .fill(dotColor.opacity(0.3))
.frame(width: 16, height: 16)
.scaleEffect(isPulsing ? 1.4 : 0.8)
.opacity(isPulsing ? 0 : 0.6)
@@ -95,24 +108,28 @@ private struct MinimalDotView: View {
private var dotColor: Color {
switch status {
- case .needsInput, .error: return .orange
- case .idle: return .secondary.opacity(0.4)
- case .completed: return .secondary.opacity(0.3)
- default: return .secondary.opacity(0.4)
+ case .needsInput, .error:
+ return theme.waitingColor(for: waitingReason)
+ case .idle: return theme.tertiaryText
+ case .completed: return theme.tertiaryText.opacity(0.7)
+ default: return theme.tertiaryText
}
}
}
+// MARK: - Claude Sparkle
+
struct ClaudeSparkleView: View {
private static let phases: [String] = ["·", "✢", "✳", "✶", "✻", "✽"]
private static let cycle: [String] = phases + phases.dropFirst().dropLast().reversed()
+ @Environment(\.theme) private var theme
@State private var currentIndex = 0
private let timer = Timer.publish(every: 0.22, on: .main, in: .common).autoconnect()
var body: some View {
Text(Self.cycle[currentIndex])
.font(.system(size: 12))
- .foregroundStyle(.secondary.opacity(opacity))
+ .foregroundStyle(theme.primaryText.opacity(opacity))
.onReceive(timer) { _ in
currentIndex = (currentIndex + 1) % Self.cycle.count
}
diff --git a/CodePulse-macOS/Views/Theme.swift b/CodePulse-macOS/Views/Theme.swift
index de19116e..b4efdbc4 100644
--- a/CodePulse-macOS/Views/Theme.swift
+++ b/CodePulse-macOS/Views/Theme.swift
@@ -1,5 +1,9 @@
import SwiftUI
+import CodePulseShared
+/// CodePulse design system inspired by Vercel/Cursor.
+/// Panel mode: pure black + single-source opacity hierarchy.
+/// Standard mode: light/dark adaptive colors.
struct CodePulseTheme {
let isDark: Bool
let isPanel: Bool
@@ -9,30 +13,94 @@ struct CodePulseTheme {
self.isPanel = isPanel
}
+ // MARK: - Base foreground (single-source opacity system for panel)
+
+ /// Panel uses #ededed as the single source color, varied by opacity.
+ private static let panelForeground = Color(red: 0.93, green: 0.93, blue: 0.93)
+
+ // MARK: - Backgrounds
+
var background: Color {
if isPanel { return .black }
return isDark ? Color(red: 0.11, green: 0.11, blue: 0.12) : .white
}
+
+ /// Elevated surface for cards/stats — Vercel uses #111 or white 4-5%
var cardBackground: Color {
- if isPanel { return Color.white.opacity(0.08) }
- return isDark ? Color.white.opacity(0.05) : Color.black.opacity(0.03)
+ if isPanel { return .white.opacity(0.05) }
+ return isDark ? .white.opacity(0.05) : .black.opacity(0.03)
+ }
+
+ /// Hover/press state — Cursor uses white 6%
+ var hoverBackground: Color {
+ if isPanel { return .white.opacity(0.06) }
+ return isDark ? .white.opacity(0.06) : .black.opacity(0.04)
+ }
+
+ var pressedBackground: Color {
+ if isPanel { return .white.opacity(0.10) }
+ return isDark ? .white.opacity(0.10) : .black.opacity(0.08)
}
+
+ // MARK: - Text hierarchy (opacity-based for panel)
+
var primaryText: Color {
- if isPanel { return Color(red: 0.96, green: 0.96, blue: 0.97) }
- return isDark ? Color(red: 0.96, green: 0.96, blue: 0.97) : Color(red: 0.11, green: 0.11, blue: 0.12)
+ if isPanel { return Self.panelForeground }
+ return isDark ? Color(red: 0.93, green: 0.93, blue: 0.93) : Color(red: 0.11, green: 0.11, blue: 0.12)
}
+
+ /// 55% opacity — Cursor's secondary text
var secondaryText: Color {
- if isPanel { return Color(red: 0.56, green: 0.56, blue: 0.58) }
- return isDark ? Color(red: 0.56, green: 0.56, blue: 0.58) : Color(red: 0.53, green: 0.53, blue: 0.55)
+ if isPanel { return Self.panelForeground.opacity(0.55) }
+ return isDark ? .white.opacity(0.55) : .black.opacity(0.50)
}
+
+ /// 35% opacity — captions, timestamps
+ var tertiaryText: Color {
+ if isPanel { return Self.panelForeground.opacity(0.35) }
+ return isDark ? .white.opacity(0.35) : .black.opacity(0.35)
+ }
+
+ // MARK: - Borders & separators — Vercel uses #242424 ≈ white 8%
+
var separator: Color {
- if isPanel { return Color.white.opacity(0.12) }
- return isDark ? Color.white.opacity(0.1) : Color.black.opacity(0.08)
+ if isPanel { return .white.opacity(0.08) }
+ return isDark ? .white.opacity(0.10) : .black.opacity(0.08)
+ }
+
+ var border: Color {
+ if isPanel { return .white.opacity(0.08) }
+ return isDark ? .white.opacity(0.10) : .black.opacity(0.10)
}
+
+ var borderHover: Color {
+ if isPanel { return .white.opacity(0.15) }
+ return isDark ? .white.opacity(0.18) : .black.opacity(0.18)
+ }
+
+ // MARK: - Semantic colors
+
var accent: Color { .blue }
- var warning: Color { .orange }
+
+ /// Attention state — bright white on panel, orange on standard
+ var warning: Color {
+ isPanel ? Self.panelForeground : .orange
+ }
+
+ /// Permission alert — bright white on panel, red on standard
+ var danger: Color {
+ isPanel ? Self.panelForeground : .red.opacity(0.85)
+ }
+
+ /// Color for a waiting session based on its reason.
+ /// Permission prompt = danger (red), everything else = warning (yellow/orange).
+ func waitingColor(for reason: WaitingReason?) -> Color {
+ reason?.isPermission == true ? danger : warning
+ }
}
+// MARK: - Environment
+
private struct ThemeKey: EnvironmentKey {
static let defaultValue = CodePulseTheme(isDark: false)
}
diff --git a/CodePulseShared/Sources/CloudKit/CKRecordMapper.swift b/CodePulseShared/Sources/CloudKit/CKRecordMapper.swift
index 73f377cf..87bffb13 100644
--- a/CodePulseShared/Sources/CloudKit/CKRecordMapper.swift
+++ b/CodePulseShared/Sources/CloudKit/CKRecordMapper.swift
@@ -14,6 +14,7 @@ public enum CKRecordMapper {
record["model"] = session.model as CKRecordValue
record["summary"] = session.summary as CKRecordValue
record["currentTask"] = (session.currentTask ?? "") as CKRecordValue
+ record["waitingReason"] = (session.waitingReason?.rawValue ?? "") as CKRecordValue
record["contextPct"] = session.contextPct as CKRecordValue
record["costUSD"] = session.costUSD as CKRecordValue
record["startedAt"] = session.startedAt as CKRecordValue
@@ -35,6 +36,7 @@ public enum CKRecordMapper {
record["model"] = session.model as CKRecordValue
record["summary"] = session.summary as CKRecordValue
record["currentTask"] = (session.currentTask ?? "") as CKRecordValue
+ record["waitingReason"] = (session.waitingReason?.rawValue ?? "") as CKRecordValue
record["contextPct"] = session.contextPct as CKRecordValue
record["costUSD"] = session.costUSD as CKRecordValue
record["startedAt"] = session.startedAt as CKRecordValue
@@ -54,6 +56,7 @@ public enum CKRecordMapper {
if let tasksData = record["tasks"] as? Data {
tasks = (try? JSONDecoder().decode([TaskItem].self, from: tasksData)) ?? []
}
+ let waitingReason = (record["waitingReason"] as? String).flatMap(WaitingReason.init)
return SessionState(
sessionId: sessionId,
projectName: record["projectName"] as? String ?? "",
@@ -62,6 +65,7 @@ public enum CKRecordMapper {
model: record["model"] as? String ?? "Unknown",
summary: record["summary"] as? String ?? "",
currentTask: record["currentTask"] as? String,
+ waitingReason: waitingReason,
tasks: tasks,
contextPct: record["contextPct"] as? Int ?? 0,
costUSD: record["costUSD"] as? Double ?? 0,
diff --git a/CodePulseShared/Sources/Models/SessionState.swift b/CodePulseShared/Sources/Models/SessionState.swift
index ff8a6dcd..d4db9b28 100644
--- a/CodePulseShared/Sources/Models/SessionState.swift
+++ b/CodePulseShared/Sources/Models/SessionState.swift
@@ -9,6 +9,7 @@ public struct SessionState: Codable, Identifiable, Equatable, Sendable {
public var summary: String
public var currentTask: String?
public var lastEvent: String?
+ public var waitingReason: WaitingReason?
public var tasks: [TaskItem]
public var contextPct: Int
public var costUSD: Double
@@ -34,7 +35,8 @@ public struct SessionState: Codable, Identifiable, Equatable, Sendable {
public init(
sessionId: String, projectName: String, gitBranch: String,
status: SessionStatus, model: String, summary: String,
- currentTask: String? = nil, lastEvent: String? = nil, tasks: [TaskItem] = [],
+ currentTask: String? = nil, lastEvent: String? = nil,
+ waitingReason: WaitingReason? = nil, tasks: [TaskItem] = [],
contextPct: Int = 0, costUSD: Double = 0,
startedAt: Date = Date(), durationSec: Int = 0,
deviceId: String = "", updatedAt: Date = Date()
@@ -47,6 +49,7 @@ public struct SessionState: Codable, Identifiable, Equatable, Sendable {
self.summary = summary
self.currentTask = currentTask
self.lastEvent = lastEvent
+ self.waitingReason = waitingReason
self.tasks = tasks
self.contextPct = contextPct
self.costUSD = costUSD
diff --git a/CodePulseShared/Sources/Models/SessionStatus.swift b/CodePulseShared/Sources/Models/SessionStatus.swift
index af54869a..519dafcb 100644
--- a/CodePulseShared/Sources/Models/SessionStatus.swift
+++ b/CodePulseShared/Sources/Models/SessionStatus.swift
@@ -8,17 +8,6 @@ public enum SessionStatus: String, Codable, Sendable {
case error
case completed
- public var color: Color {
- switch self {
- case .working: return .blue
- case .idle: return .secondary
- case .needsInput: return .orange
- case .compacting: return .purple
- case .error: return .orange
- case .completed: return .gray
- }
- }
-
public var label: String {
switch self {
case .working: return "Working"
@@ -37,3 +26,34 @@ public enum SessionStatus: String, Codable, Sendable {
}
}
}
+
+public enum WaitingReason: String, Codable, Sendable {
+ case permissionPrompt // Red — needs permission approval
+ case commandComplete // Yellow — Stop hook, command finished
+ case askUserQuestion // Yellow — AskUserQuestion tool
+ case elicitation // Yellow — elicitation dialog
+ case unknown // Yellow — fallback
+
+ public var label: String {
+ switch self {
+ case .permissionPrompt: return "Needs Permission"
+ case .commandComplete: return "Waiting for Input"
+ case .askUserQuestion: return "Question"
+ case .elicitation: return "Waiting for Input"
+ case .unknown: return "Needs Input"
+ }
+ }
+
+ public var isPermission: Bool { self == .permissionPrompt }
+}
+
+/// Type-safe hook signal types between ClaudeHookServer and TranscriptWatcher.
+public enum HookSignalType: String, Sendable {
+ case permissionRequest = "permission_request"
+ case askUserQuestion = "ask_user_question"
+ case elicitationDialog = "elicitation_dialog"
+ case stop
+ case userPromptSubmit = "user_prompt_submit"
+ case preToolUse = "pre_tool_use"
+ case postToolUse = "post_tool_use"
+}