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: add TranscriptWatcher for JSONL incremental state detection

libokaiea09dd138159
diff --git a/CodePulse-macOS/Services/TranscriptWatcher.swift b/CodePulse-macOS/Services/TranscriptWatcher.swift
new file mode 100644
index 00000000..109121b8
--- /dev/null
+++ b/CodePulse-macOS/Services/TranscriptWatcher.swift
@@ -0,0 +1,280 @@
+import Foundation
+import os
+
+private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "TranscriptWatcher")
+
+/// Per-session transcript state derived from incremental JSONL parsing
+struct TranscriptState: Sendable {
+ var status: TranscriptStatus = .idle
+ var lastEvent: String = ""
+ var toolName: String?
+ var model: String = "Unknown"
+ var latestInputTokens: Int = 0
+ var totalOutputTokens: Int = 0
+ var lastActivityTime: Date = Date()
+
+ var contextPct: Int {
+ guard latestInputTokens > 0 else { return 0 }
+ return min(100, (latestInputTokens * 100) / 200_000)
+ }
+
+ var costUSD: Double {
+ let (inputRate, outputRate) = modelPricing
+ return Double(latestInputTokens) * inputRate / 1_000_000
+ + Double(totalOutputTokens) * outputRate / 1_000_000
+ }
+
+ private var modelPricing: (Double, Double) {
+ if model.contains("opus") { return (15.0, 75.0) }
+ if model.contains("sonnet") { return (3.0, 15.0) }
+ if model.contains("haiku") { return (0.25, 1.25) }
+ return (3.0, 15.0)
+ }
+}
+
+enum TranscriptStatus: Sendable {
+ case working
+ case waitingForUser
+ case idle
+}
+
+/// Incrementally parses JSONL transcript files to detect session state.
+/// Replaces hook-based detection — zero impact on Claude Code.
+@MainActor
+final class TranscriptWatcher {
+ /// Per-session tracking
+ private struct SessionTracker {
+ var fileOffset: UInt64 = 0
+ var lineBuffer: String = ""
+ var state: TranscriptState = TranscriptState()
+ var activeToolIds: Set<String> = []
+ var hadToolsInTurn: Bool = false
+ var lastToolStartTime: Date?
+ }
+
+ private var trackers: [String: SessionTracker] = [:]
+ private let decoder = JSONDecoder()
+
+ /// Permission timeout — if a tool starts but no result comes back within this interval,
+ /// assume Claude is waiting for permission approval.
+ private let permissionTimeoutSeconds: TimeInterval = 8.0
+
+ /// Idle timeout — if no new data after turn ends, consider session idle.
+ private let idleTimeoutSeconds: TimeInterval = 10.0
+
+ // MARK: - Public API
+
+ /// Get current transcript state for a session. Returns nil if not yet tracked.
+ func state(for sessionId: String) -> TranscriptState? {
+ trackers[sessionId]?.state
+ }
+
+ /// Process new data from a session's JSONL file. Call this on each scan cycle.
+ func update(sessionId: String, jsonlURL: URL) {
+ var tracker = trackers[sessionId] ?? SessionTracker()
+
+ // Read new bytes from the file
+ guard let fileHandle = try? FileHandle(forReadingFrom: jsonlURL) else { return }
+ defer { try? fileHandle.close() }
+
+ let fileSize = fileHandle.seekToEndOfFile()
+
+ // First time seeing this session — skip to end (don't replay history)
+ if tracker.fileOffset == 0 && trackers[sessionId] == nil {
+ tracker.fileOffset = fileSize
+ // Still extract model/cost from tail for initial display
+ let info = JSONLTailReader.extractInfo(url: jsonlURL)
+ tracker.state.model = info.model
+ tracker.state.latestInputTokens = info.latestInputTokens
+ tracker.state.totalOutputTokens = info.totalOutputTokens
+ trackers[sessionId] = tracker
+ return
+ }
+
+ guard fileSize > tracker.fileOffset else {
+ // No new data — check timeouts
+ updateTimeouts(&tracker)
+ trackers[sessionId] = tracker
+ return
+ }
+
+ // Read new bytes
+ fileHandle.seek(toFileOffset: tracker.fileOffset)
+ guard let newData = try? fileHandle.readToEnd(),
+ let newText = String(data: newData, encoding: .utf8) else {
+ trackers[sessionId] = tracker
+ return
+ }
+
+ tracker.fileOffset = fileSize
+ tracker.state.lastActivityTime = Date()
+
+ // Parse lines (handle partial lines with lineBuffer)
+ let text = tracker.lineBuffer + newText
+ var lines = text.components(separatedBy: "\n")
+ tracker.lineBuffer = lines.removeLast() // May be incomplete
+
+ for line in lines where !line.isEmpty {
+ processLine(line, tracker: &tracker)
+ }
+
+ trackers[sessionId] = tracker
+ }
+
+ /// Remove tracking for a session (when it completes)
+ func removeSession(_ sessionId: String) {
+ trackers.removeValue(forKey: sessionId)
+ }
+
+ // MARK: - Line Processing
+
+ private func processLine(_ line: String, tracker: inout SessionTracker) {
+ guard let data = line.data(using: .utf8),
+ let entry = try? decoder.decode(JSONLTranscriptEntry.self, from: data) else { return }
+
+ switch entry.type {
+ case "assistant":
+ processAssistant(entry, tracker: &tracker)
+ case "user":
+ processUser(entry, tracker: &tracker)
+ case "system":
+ processSystem(entry, tracker: &tracker)
+ default:
+ break
+ }
+ }
+
+ private func processAssistant(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
+ guard let message = entry.message else { return }
+
+ // Update model and usage
+ if let model = message.model, !model.isEmpty {
+ tracker.state.model = model
+ }
+ if let usage = message.usage {
+ let inputTokens = usage.inputTokens ?? 0
+ let cacheRead = usage.cacheReadInputTokens ?? 0
+ if inputTokens > 0 {
+ tracker.state.latestInputTokens = inputTokens + cacheRead
+ }
+ tracker.state.totalOutputTokens += usage.outputTokens ?? 0
+ }
+
+ // Check content blocks for tool_use
+ guard let content = message.content else { return }
+ let toolUseBlocks = content.filter { $0.type == "tool_use" }
+
+ if !toolUseBlocks.isEmpty {
+ tracker.state.status = .working
+ tracker.hadToolsInTurn = true
+
+ for block in toolUseBlocks {
+ if let id = block.id {
+ tracker.activeToolIds.insert(id)
+ }
+ if let name = block.name {
+ tracker.state.toolName = name
+ tracker.state.lastEvent = formatToolStatus(name: name, input: block.input)
+ }
+ }
+ tracker.lastToolStartTime = Date()
+ } else if content.contains(where: { $0.type == "text" }) {
+ // Text-only response — agent is working (generating text)
+ tracker.state.status = .working
+ tracker.state.lastEvent = "Thinking..."
+ }
+ }
+
+ private func processUser(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
+ guard let content = entry.message?.content else { return }
+
+ let toolResults = content.filter { $0.type == "tool_result" }
+
+ if !toolResults.isEmpty {
+ // Tool completed
+ for result in toolResults {
+ if let id = result.toolUseId {
+ tracker.activeToolIds.remove(id)
+ }
+ }
+ if tracker.activeToolIds.isEmpty {
+ tracker.hadToolsInTurn = false
+ tracker.lastToolStartTime = nil
+ }
+ } else {
+ // New user prompt — new turn starting
+ tracker.state.status = .working
+ tracker.state.lastEvent = "Processing prompt..."
+ tracker.activeToolIds.removeAll()
+ tracker.hadToolsInTurn = false
+ tracker.lastToolStartTime = nil
+ }
+ }
+
+ private func processSystem(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
+ if entry.subtype == "turn_duration" {
+ // Definitive turn end — agent finished, waiting for user
+ tracker.state.status = .waitingForUser
+ tracker.state.lastEvent = "Waiting for input"
+ tracker.activeToolIds.removeAll()
+ tracker.hadToolsInTurn = false
+ tracker.lastToolStartTime = nil
+ }
+ }
+
+ // MARK: - Timeout Checks
+
+ private func updateTimeouts(_ tracker: inout SessionTracker) {
+ let now = Date()
+
+ // Permission heuristic: tool started but no result after timeout
+ if !tracker.activeToolIds.isEmpty,
+ let toolStart = tracker.lastToolStartTime,
+ now.timeIntervalSince(toolStart) > permissionTimeoutSeconds {
+ if tracker.state.status == .working {
+ tracker.state.status = .waitingForUser
+ tracker.state.lastEvent = "Needs permission"
+ }
+ }
+
+ // Idle timeout: no new data for a while after waiting
+ if tracker.state.status == .waitingForUser,
+ now.timeIntervalSince(tracker.state.lastActivityTime) > idleTimeoutSeconds {
+ tracker.state.status = .idle
+ }
+ }
+
+ // MARK: - Display Formatting
+
+ private func formatToolStatus(name: String, input: JSONLToolInput?) -> String {
+ switch name {
+ case "Read":
+ if let fp = input?.filePath { return "Reading \(URL(fileURLWithPath: fp).lastPathComponent)" }
+ return "Reading file"
+ case "Edit":
+ if let fp = input?.filePath { return "Editing \(URL(fileURLWithPath: fp).lastPathComponent)" }
+ return "Editing file"
+ case "Write":
+ if let fp = input?.filePath { return "Writing \(URL(fileURLWithPath: fp).lastPathComponent)" }
+ return "Writing file"
+ case "Bash":
+ if let cmd = input?.command {
+ let short = cmd.prefix(40)
+ return "Running: \(short)\(cmd.count > 40 ? "..." : "")"
+ }
+ return "Running command"
+ case "Glob":
+ return "Searching files"
+ case "Grep":
+ return "Searching code"
+ case "Agent":
+ return "Running sub-agent"
+ case "WebFetch":
+ return "Fetching web content"
+ case "WebSearch":
+ return "Searching the web"
+ default:
+ return "Using \(name)"
+ }
+ }
+}
diff --git a/CodePulse.xcodeproj/project.pbxproj b/CodePulse.xcodeproj/project.pbxproj
index 7f63bab1..b5d41c2d 100644
--- a/CodePulse.xcodeproj/project.pbxproj
+++ b/CodePulse.xcodeproj/project.pbxproj
@@ -30,6 +30,8 @@
D4BC114BC4A6C08EECD54925 /* CodePulseShared in Frameworks */ = {isa = PBXBuildFile; productRef = 7660B5D6DD8CC2065A9F4ED3 /* CodePulseShared */; };
DBD957B5BFDEC3B62B310F8F /* IOSRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF291DF4A4EF932B774F227D /* IOSRootView.swift */; };
E1740D692C1C19693058D20B /* SessionRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD09204E8CD3C16D75BA3048 /* SessionRowView.swift */; };
+ F1E2D3C4B5A6F7E8D9C0B1A2 /* SessionTagView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1F2 /* SessionTagView.swift */; };
+ D2A3B4C5E6F7081920314253 /* TranscriptWatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3C4D5E6F708192A3B4C5D6E /* TranscriptWatcher.swift */; };
E36D87A2D2D0F1177F263772 /* CodePulseLiveActivityBundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BCD1168005B123A7F9ACB37 /* CodePulseLiveActivityBundle.swift */; };
EB132AF39AB968D2DFA6151B /* CodePulseApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A67A3CD19408484AB11BB73 /* CodePulseApp.swift */; };
EDCB66A65FD85B26FE7B4664 /* SessionScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42BAF66F7C50D732B7E69333 /* SessionScanner.swift */; };
@@ -84,6 +86,7 @@
A01A225437E7A00B3337883E /* IOSSessionListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSSessionListView.swift; sourceTree = "<group>"; };
A19BA18A6829F0BE991D4C7D /* SessionFileParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionFileParser.swift; sourceTree = "<group>"; };
AD09204E8CD3C16D75BA3048 /* SessionRowView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionRowView.swift; sourceTree = "<group>"; };
+ A1B2C3D4E5F6A7B8C9D0E1F2 /* SessionTagView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionTagView.swift; sourceTree = "<group>"; };
B0BB716E74E8D313F6E7FF77 /* ProgressBarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProgressBarView.swift; sourceTree = "<group>"; };
CADC1A963B2C1124F480F9CE /* LiveActivityManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivityManager.swift; sourceTree = "<group>"; };
CD5A99B72DC7E1F01D755DF6 /* CodePulse.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = CodePulse.entitlements; sourceTree = "<group>"; };
@@ -94,6 +97,7 @@
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; path = CodePulseShared; sourceTree = SOURCE_ROOT; };
+ B3C4D5E6F708192A3B4C5D6E /* TranscriptWatcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TranscriptWatcher.swift; sourceTree = "<group>"; };
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 */
@@ -205,6 +209,7 @@
D10CABFC27BF22D45064777A /* SessionDetailView.swift */,
DA699D0197B8A14FD7D1BDC4 /* SessionListView.swift */,
AD09204E8CD3C16D75BA3048 /* SessionRowView.swift */,
+ A1B2C3D4E5F6A7B8C9D0E1F2 /* SessionTagView.swift */,
CEED6193555CB3FAC1BA7E2A /* StatusDotView.swift */,
);
path = Views;
@@ -237,6 +242,7 @@
A19BA18A6829F0BE991D4C7D /* SessionFileParser.swift */,
42BAF66F7C50D732B7E69333 /* SessionScanner.swift */,
F71E03612F167D883C324D25 /* SessionStateManager.swift */,
+ B3C4D5E6F708192A3B4C5D6E /* TranscriptWatcher.swift */,
);
path = Services;
sourceTree = "<group>";
@@ -401,9 +407,11 @@
73382915E3200DDC5EF16C2F /* SessionFileParser.swift in Sources */,
0294408FF2BC2367453C118C /* SessionListView.swift in Sources */,
E1740D692C1C19693058D20B /* SessionRowView.swift in Sources */,
+ F1E2D3C4B5A6F7E8D9C0B1A2 /* SessionTagView.swift in Sources */,
EDCB66A65FD85B26FE7B4664 /* SessionScanner.swift in Sources */,
6A5A77C9C3AF37A8E371F5CB /* SessionStateManager.swift in Sources */,
21DBF9BED5F40E2F671CB1F9 /* StatusDotView.swift in Sources */,
+ D2A3B4C5E6F7081920314253 /* TranscriptWatcher.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};