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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: TTY-based session resolution + sort by activity
libokaife13b16e99d4
diff --git a/CodePulse-macOS/Services/ClaudeHookServer.swift b/CodePulse-macOS/Services/ClaudeHookServer.swiftindex 6b0be9e7..289a47b2 100644--- a/CodePulse-macOS/Services/ClaudeHookServer.swift+++ b/CodePulse-macOS/Services/ClaudeHookServer.swift@@ -18,10 +18,12 @@ final class ClaudeHookServer: @unchecked Sendable {private var _stopSessions: Set<String> = []private var _toolRunningSessions: Set<String> = []- /// 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] = [:]+ /// All sessionIds seen from hook events, grouped by cwd.+ private var _cwdToSessionIds: [String: Set<String>] = [:]++ /// Maps TTY → sessionId. TTY uniquely identifies a terminal,+ /// so this correctly resolves multiple sessions in the same cwd.+ private var _ttyToSessionId: [String: String] = [:]// MARK: - Thread-safe accessors@@ -51,13 +53,23 @@ final class ClaudeHookServer: @unchecked Sendable {_permissionSessions.formIntersection(activeSessionIds)_stopSessions.formIntersection(activeSessionIds)_toolRunningSessions.formIntersection(activeSessionIds)+ // Prune cwd and tty mappings+ for (cwd, ids) in _cwdToSessionIds {+ let pruned = ids.intersection(activeSessionIds)+ _cwdToSessionIds[cwd] = pruned.isEmpty ? nil : pruned+ }+ _ttyToSessionId = _ttyToSessionId.filter { activeSessionIds.contains($0.value) }}}- /// 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] }+ /// Get all sessionIds seen from hooks for a cwd.+ func activeSessionIds(forCwd cwd: String) -> Set<String> {+ withLock { _cwdToSessionIds[cwd] ?? [] }+ }++ /// Get the sessionId for a specific TTY device.+ func sessionId(forTty tty: String) -> String? {+ withLock { _ttyToSessionId[tty] }}// MARK: - Callbacks@@ -106,9 +118,31 @@ final class ClaudeHookServer: @unchecked Sendable {try? FileManager.default.createDirectory(at: scriptDir, withIntermediateDirectories: true)+ // Detect TTY from parent process chain (like cc-status-bar's TtyDetector).+ // This uniquely identifies which terminal the hook fired from,+ // allowing us to distinguish multiple sessions in the same cwd.let script = """#!/bin/bashINPUT=$(cat)++ # Detect TTY from ancestor processes+ TTY=""+ PID=$$+ for i in 1 2 3 4 5; do+ T=$(ps -o tty= -p $PID 2>/dev/null | tr -d ' ')+ if [ -n "$T" ] && [ "$T" != "??" ]; then+ TTY="/dev/$T"+ break+ fi+ PID=$(ps -o ppid= -p $PID 2>/dev/null | tr -d ' ')+ [ -z "$PID" ] || [ "$PID" = "0" ] && break+ done++ # Inject tty into the JSON payload (use | as sed delimiter to avoid /dev/ conflicts)+ if [ -n "$TTY" ]; then+ INPUT=$(echo "$INPUT" | sed 's|}$|,"tty":"'"$TTY"'"}|')+ fi+curl -s --max-time 1 -X POST "http://127.0.0.1:\(port)/codepulse-event" \-H "Content-Type: application/json" \-d "$INPUT" 2>/dev/null &@@ -251,11 +285,14 @@ final class ClaudeHookServer: @unchecked Sendable {let toolName = json["tool_name"] as? Stringlet 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.+ let tty = json["tty"] as? String++ // Track sessionId by cwd and by TTYif let sessionId, let cwd {- withLock { _cwdToSessionId[cwd] = sessionId }+ withLock {+ _cwdToSessionIds[cwd, default: []].insert(sessionId)+ if let tty { _ttyToSessionId[tty] = sessionId }+ }}switch eventName {@@ -297,16 +334,16 @@ final class ClaudeHookServer: @unchecked Sendable {case "SessionStart":logger.info("SessionStart\(sessionId.map { " \($0.prefix(8))..." } ?? "")")- DispatchQueue.main.async { [weak self] in self?.onSessionEvent?() }+ Task { @MainActor [weak self] in self?.onSessionEvent?() }case "SessionEnd":guard let sessionId else {- DispatchQueue.main.async { [weak self] in self?.onSessionEvent?() }+ Task { @MainActor [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?() }+ Task { @MainActor [weak self] in self?.onSessionEvent?() }default:break@@ -314,7 +351,7 @@ final class ClaudeHookServer: @unchecked Sendable {}private func emit(_ sessionId: String, _ signal: HookSignalType, _ toolName: String?) {- DispatchQueue.main.async { [weak self] in+ Task { @MainActor [weak self] inself?.onHookSignal?(sessionId, signal, toolName)self?.onSessionEvent?()}diff --git a/CodePulse-macOS/Services/SessionScanner.swift b/CodePulse-macOS/Services/SessionScanner.swiftindex 55b3b13e..c4b3174c 100644--- a/CodePulse-macOS/Services/SessionScanner.swift+++ b/CodePulse-macOS/Services/SessionScanner.swift@@ -8,7 +8,6 @@ private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "Sessionfinal class SessionScanner: ObservableObject {@Published var activeSessions: [String: RawSessionFile] = [:]- /// Reference to the hook server for cwd→sessionId resolutionvar hookServer: ClaudeHookServer?private var sessionsWatcher: DispatchSourceFileSystemObject?@@ -26,7 +25,7 @@ final class SessionScanner: ObservableObject {self?.scan()}}- logger.info("SessionScanner started, watching \(ClaudePaths.sessionsDir.path)")+ logger.info("SessionScanner started")}func stop() {@@ -46,7 +45,6 @@ final class SessionScanner: ObservableObject {}}- /// Called from hook events — uses the same debounce to avoid redundant scans.func scheduleScanFromHook() {scheduleScan()}@@ -55,17 +53,19 @@ final class SessionScanner: ObservableObject {let files = SessionFileParser.parseSessionFiles()var newSessions: [String: RawSessionFile] = [:]+ var alivePids = Set<Int>()for file in files {guard PIDChecker.isAlive(pid: file.pid) else { continue }-- // 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+ alivePids.insert(file.pid)let resolved = resolveSessionId(file)+ // Dict keyed by sessionId — if two PIDs resolve to the same JSONL,+ // the later one wins (acceptable: they share the same transcript)newSessions[resolved.sessionId] = resolved}+ // Clean up TTY cache for dead PIDs+ ttyCache = ttyCache.filter { alivePids.contains($0.key) }+if newSessions != activeSessions {if newSessions.count != activeSessions.count {logger.info("Active sessions: \(newSessions.count)")@@ -74,28 +74,45 @@ final class SessionScanner: ObservableObject {}}- /// 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.+ // MARK: - Session ID Resolution+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 {+ // 1. TTY-based resolution (most precise — each terminal has a unique TTY)+ if let tty = detectAndCacheTty(pid: file.pid),+ let hookSessionId = hookServer?.sessionId(forTty: tty) {return RawSessionFile(pid: file.pid, sessionId: hookSessionId, cwd: file.cwd, startedAt: file.startedAt)}- // 2. Check if original JSONL exists — if so, no resolution needed+ // 2. Original JSONL exists — use itlet 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+ // 3. Hook server cwd-based (when only 1 session per cwd, unambiguous)+ let hookIds = hookServer?.activeSessionIds(forCwd: file.cwd) ?? []+ if hookIds.count == 1, let hookId = hookIds.first {+ let hookJsonl = ClaudePaths.jsonlPath(cwd: file.cwd, sessionId: hookId)+ if FileManager.default.fileExists(atPath: hookJsonl.path) {+ return RawSessionFile(pid: file.pid, sessionId: hookId, cwd: file.cwd, startedAt: file.startedAt)+ }+ }++ // 4. Last resort: most recently modified JSONL in the project directoryreturn 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.+ // MARK: - TTY Cache (caches both hits and misses to avoid repeated subprocess spawns)++ private var ttyCache: [Int: String?] = [:]++ private func detectAndCacheTty(pid: Int) -> String? {+ if let cached = ttyCache[pid] { return cached }+ let tty = PIDChecker.tty(for: pid)+ ttyCache[pid] = tty // cache nil too — avoids retrying every 5s+ return tty+ }+private func resolveFromJsonlDirectory(_ file: RawSessionFile) -> RawSessionFile {let projectDir = ClaudePaths.projectsDir.appendingPathComponent(ClaudePaths.mangledCwd(file.cwd))@@ -125,29 +142,18 @@ final class SessionScanner: ObservableObject {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 RawSessionFile(pid: file.pid, sessionId: activeSessionId, cwd: file.cwd, startedAt: file.startedAt)}return file}+ // MARK: - Directory Watching+private func watchDirectory(_ url: URL, handler: @escaping () -> Void) {let fd = open(url.path, O_EVTONLY)- guard fd >= 0 else {- logger.warning("Failed to watch directory: \(url.path)")- return- }+ guard fd >= 0 else { return }let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd,eventMask: [.write, .rename, .delete],diff --git a/CodePulse-macOS/Services/SessionStateManager.swift b/CodePulse-macOS/Services/SessionStateManager.swiftindex 2443fa44..7ee89a27 100644--- a/CodePulse-macOS/Services/SessionStateManager.swift+++ b/CodePulse-macOS/Services/SessionStateManager.swift@@ -124,10 +124,16 @@ final class SessionStateManager: ObservableObject {}}- let newSessions = updated.sorted { $0.startedAt > $1.startedAt }- if newSessions != sessions {- sessions = newSessions+ // Sort: working first, then by most recent activity+ let newSessions = updated.sorted { a, b in+ let aWeight = a.status == .working ? 0 : a.status == .needsInput ? 1 : 2+ let bWeight = b.status == .working ? 0 : b.status == .needsInput ? 1 : 2+ if aWeight != bWeight { return aWeight < bWeight }+ return a.updatedAt > b.updatedAt}+ // Always assign — hook state changes (status, waitingReason) must propagate+ // to UI even when the session list structure hasn't changed+ sessions = newSessions}private var skipPermissionsCache: [Int: Bool] = [:]diff --git a/CodePulse-macOS/Utilities/PIDChecker.swift b/CodePulse-macOS/Utilities/PIDChecker.swiftindex b244687f..09c5aacf 100644--- a/CodePulse-macOS/Utilities/PIDChecker.swift+++ b/CodePulse-macOS/Utilities/PIDChecker.swift@@ -5,22 +5,43 @@ enum PIDChecker {kill(Int32(pid), 0) == 0}- /// Check if a process was launched with --dangerously-skip-permissions- static func skipsPermissions(pid: Int) -> Bool {+ /// Get the TTY device for a PID by walking up the process tree.+ /// Uses a single `ps -o tty=,ppid=` per iteration (max 5 subprocesses).+ static func tty(for pid: Int) -> String? {+ var current = Int32(pid)+ for _ in 0..<5 {+ guard let output = psColumns(pid: current, columns: "tty=,ppid=") else { break }+ let parts = output.split(separator: " ", maxSplits: 1)+ let tty = parts.first.map(String.init)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ if !tty.isEmpty && tty != "??" {+ return "/dev/\(tty)"+ }+ guard parts.count > 1,+ let ppid = Int32(parts[1].trimmingCharacters(in: .whitespacesAndNewlines)),+ ppid > 0 else { break }+ current = ppid+ }+ return nil+ }++ /// Run `ps -o <columns> -p <pid>` and return the output string.+ private static func psColumns(pid: Int32, columns: String) -> String? {let proc = Process()proc.executableURL = URL(fileURLWithPath: "/bin/ps")- proc.arguments = ["-p", "\(pid)", "-o", "args="]+ proc.arguments = ["-o", columns, "-p", "\(pid)"]let pipe = Pipe()proc.standardOutput = pipeproc.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- }+ guard (try? proc.run()) != nil else { return nil }+ proc.waitUntilExit()+ guard proc.terminationStatus == 0 else { return nil }+ let data = pipe.fileHandleForReading.readDataToEndOfFile()+ return String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)+ }++ /// Check if a process was launched with --dangerously-skip-permissions+ static func skipsPermissions(pid: Int) -> Bool {+ guard let args = psColumns(pid: Int32(pid), columns: "args=") else { return false }+ return args.contains("--dangerously-skip-permissions")}}