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: overhaul transcript parsing, iOS UI, and Live Activity support

libokai4da7bc5d3324
diff --git a/CodePulse-iOS/Services/LiveActivityManager.swift b/CodePulse-iOS/Services/LiveActivityManager.swift
index 02fe3c35..83f212ed 100644
--- a/CodePulse-iOS/Services/LiveActivityManager.swift
+++ b/CodePulse-iOS/Services/LiveActivityManager.swift
@@ -1,70 +1,176 @@
import ActivityKit
import Foundation
-import Combine
import UserNotifications
import CodePulseShared
+enum TrackingMode: String, CaseIterable, Sendable {
+ case auto
+ case manual
+
+ var label: String {
+ switch self {
+ case .auto: "Auto"
+ case .manual: "Manual"
+ }
+ }
+
+ var icon: String {
+ switch self {
+ case .auto: "antenna.radiowaves.left.and.right"
+ case .manual: "hand.tap"
+ }
+ }
+}
+
@MainActor
final class LiveActivityManager: ObservableObject {
- @Published var trackedSessionId: String?
- private var currentActivity: Activity<CodePulseAttributes>?
+ @Published private(set) var trackedSessionIds: Set<String> = []
+ @Published var trackingMode: TrackingMode {
+ didSet { UserDefaults.standard.set(trackingMode.rawValue, forKey: "codepulse_trackingMode") }
+ }
+ private var activities: [String: Activity<CodePulseAttributes>] = [:]
+ private var manualPins: Set<String> = [] // user-pinned sessions in manual mode
+
+ private static let maxActivities = 4
+
+ init() {
+ let saved = UserDefaults.standard.string(forKey: "codepulse_trackingMode") ?? "auto"
+ self.trackingMode = TrackingMode(rawValue: saved) ?? .auto
+ }
+
+ func isTracking(sessionId: String) -> Bool {
+ trackedSessionIds.contains(sessionId)
+ }
+
+ func isPinned(sessionId: String) -> Bool {
+ manualPins.contains(sessionId)
+ }
+
+ // Manual mode: toggle pin
+ func togglePin(_ session: SessionState) {
+ if manualPins.contains(session.sessionId) {
+ manualPins.remove(session.sessionId)
+ stopTracking(sessionId: session.sessionId)
+ } else {
+ guard manualPins.count < Self.maxActivities else { return }
+ manualPins.insert(session.sessionId)
+ startTracking(session)
+ }
+ }
+
+ func updateSessions(_ sessions: [SessionState]) {
+ // Clean up completed sessions (snapshot IDs first to avoid mutation during iteration)
+ let completedIds = trackedSessionIds.filter { id in
+ sessions.first(where: { $0.sessionId == id })?.status == .completed
+ }
+ for sessionId in completedIds {
+ if let session = sessions.first(where: { $0.sessionId == sessionId }) {
+ sendCompletionNotification(session)
+ }
+ stopTracking(sessionId: sessionId)
+ manualPins.remove(sessionId)
+ }
+
+ switch trackingMode {
+ case .auto:
+ autoUpdate(sessions)
+ case .manual:
+ manualUpdate(sessions)
+ }
+ }
+
+ // MARK: - Auto mode
+
+ /// Priority: working sessions sorted by progress desc (near-completion first), then startedAt desc (newer first)
+ private func autoUpdate(_ sessions: [SessionState]) {
+ let working = sessions
+ .filter { $0.status == .working }
+ .sorted { a, b in
+ let progressA = a.totalTaskCount > 0 ? Double(a.completedTaskCount) / Double(a.totalTaskCount) : 0
+ let progressB = b.totalTaskCount > 0 ? Double(b.completedTaskCount) / Double(b.totalTaskCount) : 0
+ if progressA != progressB { return progressA > progressB }
+ return a.startedAt > b.startedAt
+ }
+
+ let desired = Set(working.prefix(Self.maxActivities).map(\.sessionId))
+
+ // Stop tracking sessions no longer in top N (snapshot to avoid mutation during iteration)
+ let toRemove = trackedSessionIds.filter { !desired.contains($0) }
+ for sessionId in toRemove {
+ stopTracking(sessionId: sessionId)
+ }
+
+ // Start tracking new top sessions
+ for session in working.prefix(Self.maxActivities) {
+ if !isTracking(sessionId: session.sessionId) {
+ startTracking(session)
+ } else if let activity = activities[session.sessionId] {
+ let state = contentState(from: session)
+ Task { @MainActor in
+ await activity.update(.init(state: state, staleDate: nil))
+ }
+ }
+ }
+ }
+
+ // MARK: - Manual mode
+
+ private func manualUpdate(_ sessions: [SessionState]) {
+ for sessionId in manualPins {
+ guard let session = sessions.first(where: { $0.sessionId == sessionId }) else { continue }
+ if !isTracking(sessionId: sessionId) {
+ startTracking(session)
+ } else if let activity = activities[sessionId] {
+ let state = contentState(from: session)
+ Task { @MainActor in
+ await activity.update(.init(state: state, staleDate: nil))
+ }
+ }
+ }
+ }
+
+ // MARK: - Core
+
+ private func startTracking(_ session: SessionState) {
+ guard !isTracking(sessionId: session.sessionId) else { return }
+ guard trackedSessionIds.count < Self.maxActivities else { return }
- func startTracking(_ session: SessionState) {
- stopTracking()
let attributes = CodePulseAttributes(
sessionId: session.sessionId,
projectName: session.projectName
)
let state = contentState(from: session)
do {
- currentActivity = try Activity.request(
+ let activity = try Activity.request(
attributes: attributes,
content: .init(state: state, staleDate: nil),
pushType: nil
)
- trackedSessionId = session.sessionId
+ activities[session.sessionId] = activity
+ trackedSessionIds.insert(session.sessionId)
} catch {
print("Failed to start Live Activity: \(error)")
}
}
- func stopTracking() {
- let activity = currentActivity
- currentActivity = nil
- trackedSessionId = nil
+ private func stopTracking(sessionId: String) {
+ guard let activity = activities.removeValue(forKey: sessionId) else { return }
+ trackedSessionIds.remove(sessionId)
Task { @MainActor in
- await activity?.end(nil, dismissalPolicy: .immediate)
+ await activity.end(nil, dismissalPolicy: .immediate)
}
}
- func update(sessions: [SessionState]) {
- guard let trackedId = trackedSessionId else {
- if let newest = sessions.first(where: { $0.status == .working }) {
- startTracking(newest)
- }
- return
+ /// When switching modes, stop all current activities and re-evaluate
+ func onModeChanged(sessions: [SessionState]) {
+ // Stop all
+ for sessionId in Array(trackedSessionIds) {
+ stopTracking(sessionId: sessionId)
}
- guard let session = sessions.first(where: { $0.sessionId == trackedId }) else { return }
- if session.status == .completed {
- onSessionCompleted(session, allSessions: sessions)
- } else {
- let state = contentState(from: session)
- let activity = currentActivity
- Task { @MainActor in
- await activity?.update(.init(state: state, staleDate: nil))
- }
- }
- }
-
- private func onSessionCompleted(_ session: SessionState, allSessions: [SessionState]) {
- sendCompletionNotification(session)
- if let next = allSessions.first(where: { $0.status == .working && $0.sessionId != session.sessionId }) {
- startTracking(next)
- } else {
- let total = allSessions.reduce(0.0) { $0 + $1.costUSD }
- sendAllCompleteNotification(count: allSessions.count, totalCost: total)
- stopTracking()
+ if trackingMode == .auto {
+ manualPins.removeAll()
}
+ updateSessions(sessions)
}
private func contentState(from session: SessionState) -> CodePulseAttributes.ContentState {
@@ -89,13 +195,4 @@ final class LiveActivityManager: ObservableObject {
let request = UNNotificationRequest(identifier: session.sessionId, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
-
- private func sendAllCompleteNotification(count: Int, totalCost: Double) {
- let content = UNMutableNotificationContent()
- content.title = "All Sessions Complete"
- content.body = "All \(count) sessions finished · Total $\(String(format: "%.2f", totalCost))"
- content.sound = .default
- let request = UNNotificationRequest(identifier: "all-complete", content: content, trigger: nil)
- UNUserNotificationCenter.current().add(request)
- }
}
diff --git a/CodePulse-iOS/Views/IOSOnboardingView.swift b/CodePulse-iOS/Views/IOSOnboardingView.swift
index f1269844..d3842f37 100644
--- a/CodePulse-iOS/Views/IOSOnboardingView.swift
+++ b/CodePulse-iOS/Views/IOSOnboardingView.swift
@@ -1,23 +1,36 @@
import SwiftUI
struct IOSOnboardingView: View {
+ @Environment(\.theme) private var theme
+
var body: some View {
- VStack(spacing: 20) {
+ VStack(spacing: 24) {
+ Spacer()
+
Image(systemName: "waveform.path")
- .font(.system(size: 64))
- .foregroundStyle(.cyan)
- Text("CodePulse")
- .font(.title.bold())
- Text("Install CodePulse on your Mac\nto start monitoring Claude Code sessions")
- .multilineTextAlignment(.center)
- .foregroundStyle(.secondary)
- HStack(spacing: 8) {
- Circle().fill(.green).frame(width: 8, height: 8)
- Text("Waiting for connection...")
- .foregroundStyle(.secondary)
- .font(.callout)
+ .font(.system(size: 56, weight: .light))
+ .foregroundStyle(theme.secondaryText.opacity(0.6))
+
+ VStack(spacing: 8) {
+ Text("CodePulse")
+ .font(.system(size: 28, weight: .semibold, design: .rounded))
+ .foregroundStyle(theme.primaryText)
+ Text("Install CodePulse on your Mac\nto start monitoring Claude Code sessions")
+ .multilineTextAlignment(.center)
+ .font(.system(size: 15))
+ .foregroundStyle(theme.secondaryText)
}
- .padding(.top, 20)
+
+ HStack(spacing: 6) {
+ ClaudeSparkleView()
+ .frame(width: 14, height: 14)
+ Text("Waiting for sessions…")
+ .font(.system(size: 14))
+ .foregroundStyle(theme.secondaryText)
+ }
+ .padding(.top, 12)
+
+ Spacer()
}
.padding()
}
diff --git a/CodePulse-iOS/Views/IOSRootView.swift b/CodePulse-iOS/Views/IOSRootView.swift
index d4d4a856..9ad0c537 100644
--- a/CodePulse-iOS/Views/IOSRootView.swift
+++ b/CodePulse-iOS/Views/IOSRootView.swift
@@ -4,17 +4,38 @@ import CodePulseShared
struct IOSRootView: View {
@ObservedObject var receiver: CloudKitReceiver
@ObservedObject var liveActivityManager: LiveActivityManager
+ @AppStorage("codepulse_darkMode") private var isDarkMode = true
+
+ private var theme: CodePulseTheme { CodePulseTheme(isDark: isDarkMode) }
var body: some View {
NavigationStack {
- if receiver.sessions.isEmpty {
- IOSOnboardingView()
- } else {
- IOSSessionListView(sessions: receiver.sessions)
+ Group {
+ if receiver.sessions.isEmpty {
+ IOSOnboardingView()
+ } else {
+ IOSSessionListView(
+ sessions: receiver.sessions,
+ liveActivityManager: liveActivityManager
+ )
+ }
+ }
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ Button {
+ withAnimation(.easeInOut(duration: 0.2)) { isDarkMode.toggle() }
+ } label: {
+ Image(systemName: isDarkMode ? "moon.fill" : "sun.max.fill")
+ .font(.system(size: 14))
+ .foregroundStyle(theme.secondaryText)
+ }
+ }
}
}
+ .environment(\.theme, theme)
+ .preferredColorScheme(isDarkMode ? .dark : .light)
.onChange(of: receiver.sessions) { _, sessions in
- liveActivityManager.update(sessions: sessions)
+ liveActivityManager.updateSessions(sessions)
}
}
}
diff --git a/CodePulse-iOS/Views/IOSSessionDetailView.swift b/CodePulse-iOS/Views/IOSSessionDetailView.swift
index 67d14929..f61d7b51 100644
--- a/CodePulse-iOS/Views/IOSSessionDetailView.swift
+++ b/CodePulse-iOS/Views/IOSSessionDetailView.swift
@@ -3,67 +3,122 @@ import CodePulseShared
struct IOSSessionDetailView: View {
let session: SessionState
+ @Environment(\.theme) private var theme
var body: some View {
- List {
- Section {
- HStack {
- Circle().fill(session.status.color).frame(width: 10, height: 10)
- Text(session.status.label)
- Spacer()
- Text(session.model).foregroundStyle(.secondary)
+ ScrollView {
+ VStack(alignment: .leading, spacing: 16) {
+ headerSection
+ statsCard
+ if !session.tasks.isEmpty {
+ tasksSection
}
- HStack {
- Text(session.projectName)
- Spacer()
- Text(session.gitBranch).foregroundStyle(.secondary)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ }
+ .background(theme.background)
+ .navigationTitle(session.summary)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private var headerSection: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ SessionStatusView(
+ status: session.status,
+ completedTasks: session.completedTaskCount,
+ totalTasks: session.totalTaskCount
+ )
+ Text(session.status.label)
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(session.status == .needsInput ? theme.warning : theme.secondaryText)
+ Spacer()
+ if !session.model.isEmpty {
+ SessionTagView(tag: session.model)
}
}
+ HStack(spacing: 6) {
+ Label(session.projectName, systemImage: "folder")
+ if !session.gitBranch.isEmpty {
+ Text("·")
+ Text(session.gitBranch)
+ }
+ }
+ .font(.system(size: 13))
+ .foregroundStyle(theme.secondaryText)
+ }
+ }
- if !session.tasks.isEmpty {
- Section("Tasks — \(session.completedTaskCount) of \(session.totalTaskCount)") {
- IOSMiniProgressBar(tasks: session.tasks)
- .padding(.vertical, 4)
- ForEach(session.tasks) { task in
- HStack(spacing: 8) {
- taskIcon(task.status)
- Text(task.content)
- .foregroundStyle(task.status == .pending ? .secondary : .primary)
- }
- }
+ private var statsCard: some View {
+ HStack(spacing: 0) {
+ statItem("\(session.contextPct)%", "Context")
+ Divider().frame(height: 28)
+ statItem(String(format: "$%.2f", session.costUSD), "Cost")
+ Divider().frame(height: 28)
+ statItem(formatDuration(session.durationSec), "Duration")
+ }
+ .padding(.vertical, 10)
+ .background(
+ RoundedRectangle(cornerRadius: 10, style: .continuous)
+ .fill(theme.cardBackground)
+ )
+ }
+
+ private var tasksSection: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 12) {
+ DetailProgressRing(
+ completed: session.completedTaskCount,
+ total: session.totalTaskCount
+ )
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Tasks")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(theme.primaryText)
+ Text("\(session.completedTaskCount) of \(session.totalTaskCount) completed")
+ .font(.system(size: 13))
+ .foregroundStyle(theme.secondaryText)
}
+ Spacer()
}
- Section {
- HStack {
- statItem("Context", "\(session.contextPct)%")
- Divider()
- statItem("Cost", String(format: "$%.2f", session.costUSD))
- Divider()
- statItem("Time", formatDuration(session.durationSec))
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(session.tasks) { task in
+ HStack(spacing: 8) {
+ taskIcon(task.status)
+ Text(task.content)
+ .font(.system(size: 14))
+ .foregroundStyle(task.status == .pending ? theme.secondaryText : theme.primaryText)
+ .lineLimit(2)
+ }
}
- .padding(.vertical, 4)
}
}
- .navigationTitle(session.summary)
- .navigationBarTitleDisplayMode(.inline)
}
private func taskIcon(_ status: TaskStatus) -> some View {
Group {
switch status {
- case .completed: Image(systemName: "checkmark.circle.fill").foregroundStyle(.green)
- case .inProgress: Image(systemName: "circle.dotted.circle").foregroundStyle(.cyan)
- case .pending: Image(systemName: "circle").foregroundStyle(.secondary)
+ case .completed:
+ Image(systemName: "checkmark.circle.fill").foregroundStyle(.blue)
+ case .inProgress:
+ Image(systemName: "circlebadge.fill").foregroundStyle(.blue)
+ case .pending:
+ Image(systemName: "circle").foregroundStyle(theme.secondaryText)
}
}
.font(.system(size: 14))
}
- private func statItem(_ label: String, _ value: String) -> some View {
- VStack(spacing: 2) {
- Text(label).font(.caption2).foregroundStyle(.secondary)
- Text(value).font(.callout.weight(.semibold))
+ private func statItem(_ value: String, _ label: String) -> some View {
+ VStack(spacing: 3) {
+ Text(value)
+ .font(.system(size: 16, weight: .semibold, design: .rounded))
+ .foregroundStyle(theme.primaryText)
+ Text(label)
+ .font(.system(size: 11))
+ .foregroundStyle(theme.secondaryText)
}
.frame(maxWidth: .infinity)
}
@@ -71,6 +126,36 @@ struct IOSSessionDetailView: View {
private func formatDuration(_ seconds: Int) -> String {
if seconds < 60 { return "\(seconds)s" }
if seconds < 3600 { return "\(seconds / 60)m" }
- return "\(seconds / 3600)h \((seconds % 3600) / 60)m"
+ let h = seconds / 3600
+ let m = (seconds % 3600) / 60
+ return "\(h)h \(m)m"
+ }
+}
+
+private struct DetailProgressRing: View {
+ let completed: Int
+ let total: Int
+ @State private var animatedProgress: Double = 0
+
+ private var progress: Double {
+ total > 0 ? Double(completed) / Double(total) : 0
+ }
+
+ var body: some View {
+ ZStack {
+ Circle().stroke(Color.primary.opacity(0.06), lineWidth: 3.5)
+ Circle()
+ .trim(from: 0, to: animatedProgress)
+ .stroke(Color.blue, style: StrokeStyle(lineWidth: 3.5, lineCap: .round))
+ .rotationEffect(.degrees(-90))
+ Text("\(Int(progress * 100))%")
+ .font(.system(size: 12, weight: .semibold, design: .rounded))
+ .foregroundStyle(.primary)
+ }
+ .frame(width: 44, height: 44)
+ .onAppear { withAnimation(.easeOut(duration: 0.6)) { animatedProgress = progress } }
+ .onChange(of: progress) { _, newValue in
+ withAnimation(.easeOut(duration: 0.4)) { animatedProgress = newValue }
+ }
}
}
diff --git a/CodePulse-iOS/Views/IOSSessionListView.swift b/CodePulse-iOS/Views/IOSSessionListView.swift
index 1cf6df25..14f03e03 100644
--- a/CodePulse-iOS/Views/IOSSessionListView.swift
+++ b/CodePulse-iOS/Views/IOSSessionListView.swift
@@ -3,35 +3,158 @@ import CodePulseShared
struct IOSSessionListView: View {
let sessions: [SessionState]
+ @ObservedObject var liveActivityManager: LiveActivityManager
+ @Environment(\.theme) private var theme
var body: some View {
- List(sessions) { session in
+ List {
+ trackingModeSection
+ sessionsSection
+ }
+ .listStyle(.plain)
+ .navigationTitle("CodePulse")
+ }
+
+ private var trackingModeSection: some View {
+ Section {
+ HStack(spacing: 8) {
+ Image(systemName: liveActivityManager.trackingMode.icon)
+ .font(.system(size: 13))
+ .foregroundStyle(theme.accent)
+ .frame(width: 20)
+
+ Text("Live Activity")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(theme.primaryText)
+
+ Spacer()
+
+ Picker("", selection: $liveActivityManager.trackingMode) {
+ ForEach(TrackingMode.allCases, id: \.self) { mode in
+ Text(mode.label).tag(mode)
+ }
+ }
+ .pickerStyle(.segmented)
+ .frame(width: 140)
+ .onChange(of: liveActivityManager.trackingMode) { _, _ in
+ liveActivityManager.onModeChanged(sessions: sessions)
+ }
+ }
+ .padding(.vertical, 2)
+ }
+ .listRowBackground(Color.clear)
+ .listRowSeparator(.hidden)
+ }
+
+ private var sessionsSection: some View {
+ ForEach(sessions) { session in
NavigationLink(destination: IOSSessionDetailView(session: session)) {
- HStack(spacing: 10) {
- Circle()
- .fill(session.status.color)
- .frame(width: 10, height: 10)
- VStack(alignment: .leading, spacing: 2) {
- Text(session.summary)
- .font(.body.weight(.medium))
+ SessionRowContent(
+ session: session,
+ trackingMode: liveActivityManager.trackingMode,
+ isTracking: liveActivityManager.isTracking(sessionId: session.sessionId),
+ isPinned: liveActivityManager.isPinned(sessionId: session.sessionId),
+ onTogglePin: { liveActivityManager.togglePin(session) }
+ )
+ }
+ .listRowBackground(Color.clear)
+ .listRowSeparator(.hidden)
+ }
+ }
+}
+
+private struct SessionRowContent: View {
+ let session: SessionState
+ let trackingMode: TrackingMode
+ let isTracking: Bool
+ let isPinned: Bool
+ let onTogglePin: () -> Void
+ @Environment(\.theme) private var theme
+
+ var body: some View {
+ HStack(spacing: 10) {
+ SessionStatusView(
+ status: session.status,
+ completedTasks: session.completedTaskCount,
+ totalTasks: session.totalTaskCount
+ )
+
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 5) {
+ Text(session.summary)
+ .font(.system(size: 15, weight: .medium))
+ .foregroundStyle(theme.primaryText)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ if !session.model.isEmpty {
+ SessionTagView(tag: session.model)
+ }
+ }
+ HStack(spacing: 4) {
+ if let subtitle = session.lastEvent ?? session.currentTask {
+ Text(subtitle)
+ .font(.system(size: 13))
+ .foregroundStyle(session.status == .needsInput ? theme.warning : theme.secondaryText)
+ .lineLimit(1)
+ } else {
+ Text("\(session.projectName) · \(session.status.label)")
+ .font(.system(size: 13))
+ .foregroundStyle(theme.secondaryText)
.lineLimit(1)
- Text("\(session.projectName) · \(session.completedTaskCount)/\(session.totalTaskCount) tasks · \(session.status.label)")
- .font(.caption)
- .foregroundStyle(.secondary)
- if !session.tasks.isEmpty {
- IOSMiniProgressBar(tasks: session.tasks)
- }
}
+ Spacer()
+ Text(relativeTime(session.startedAt))
+ .font(.system(size: 12, design: .rounded))
+ .foregroundStyle(theme.secondaryText)
+ }
+ if !session.tasks.isEmpty {
+ MiniProgressBar(tasks: session.tasks)
}
- .padding(.vertical, 4)
}
+
+ liveActivityIndicator
}
- .navigationTitle("CodePulse")
+ .padding(.vertical, 4)
+ }
+
+ @ViewBuilder
+ private var liveActivityIndicator: some View {
+ switch trackingMode {
+ case .auto:
+ // Auto mode: just show indicator, no interaction
+ if isTracking {
+ Image(systemName: "dot.radiowaves.up.forward")
+ .font(.system(size: 13))
+ .foregroundStyle(theme.accent)
+ .frame(width: 24, height: 24)
+ }
+ case .manual:
+ // Manual mode: tappable pin button
+ Button(action: onTogglePin) {
+ Image(systemName: isPinned ? "pin.fill" : "pin")
+ .font(.system(size: 13))
+ .foregroundStyle(isPinned ? theme.accent : theme.secondaryText.opacity(0.4))
+ .frame(width: 28, height: 28)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ }
+
+ 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"
}
}
-struct IOSMiniProgressBar: View {
+private struct MiniProgressBar: View {
let tasks: [TaskItem]
+ @Environment(\.theme) private var theme
+
var body: some View {
HStack(spacing: 2) {
ForEach(tasks) { task in
@@ -40,13 +163,14 @@ struct IOSMiniProgressBar: View {
.frame(height: 3)
}
}
- .padding(.top, 2)
+ .padding(.top, 1)
}
+
private func color(for status: TaskStatus) -> Color {
switch status {
- case .completed: return .green
- case .inProgress: return .cyan
- case .pending: return Color(.systemGray4)
+ case .completed: return .blue
+ case .inProgress: return .blue.opacity(0.4)
+ case .pending: return theme.secondaryText.opacity(0.2)
}
}
}
diff --git a/CodePulse-iOS/Views/IOSSessionTagView.swift b/CodePulse-iOS/Views/IOSSessionTagView.swift
new file mode 100644
index 00000000..8fe35aa7
--- /dev/null
+++ b/CodePulse-iOS/Views/IOSSessionTagView.swift
@@ -0,0 +1,17 @@
+import SwiftUI
+
+struct SessionTagView: View {
+ let tag: String
+
+ var body: some View {
+ Text(tag)
+ .font(.system(size: 10, weight: .medium, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 4)
+ .padding(.vertical, 2)
+ .background(
+ RoundedRectangle(cornerRadius: 4, style: .continuous)
+ .fill(Color.primary.opacity(0.06))
+ )
+ }
+}
diff --git a/CodePulse-iOS/Views/IOSStatusIndicator.swift b/CodePulse-iOS/Views/IOSStatusIndicator.swift
new file mode 100644
index 00000000..0243b398
--- /dev/null
+++ b/CodePulse-iOS/Views/IOSStatusIndicator.swift
@@ -0,0 +1,126 @@
+import SwiftUI
+import CodePulseShared
+
+struct SessionStatusView: View {
+ let status: SessionStatus
+ let completedTasks: Int
+ let totalTasks: Int
+
+ private var hasTasks: Bool { totalTasks > 0 }
+ private var progress: Double {
+ totalTasks > 0 ? Double(completedTasks) / Double(totalTasks) : 0
+ }
+
+ var body: some View {
+ if hasTasks {
+ ProgressRingView(progress: progress, status: status)
+ .frame(width: 22, height: 22)
+ } else if status == .working {
+ ClaudeSparkleView()
+ .frame(width: 18, height: 18)
+ } else {
+ MinimalDotView(status: status)
+ }
+ }
+}
+
+private struct ProgressRingView: View {
+ let progress: Double
+ let status: SessionStatus
+ @State private var isPulsing = false
+
+ private var isWorking: Bool { status == .working }
+ private var needsAttention: Bool { status == .needsInput || status == .error }
+
+ var body: some View {
+ ZStack {
+ Circle()
+ .stroke(Color.primary.opacity(0.08), lineWidth: 2.5)
+ Circle()
+ .trim(from: 0, to: progress)
+ .stroke(Color.blue, style: StrokeStyle(lineWidth: 2.5, 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.5, lineCap: .round))
+ .rotationEffect(.degrees(-90))
+ .blur(radius: 1.5)
+ .opacity(isPulsing ? 1.0 : 0.3)
+ }
+ if needsAttention {
+ Circle()
+ .fill(Color.orange)
+ .frame(width: 6, height: 6)
+ .offset(x: 7, y: -7)
+ }
+ }
+ .animation(
+ isWorking ? .easeInOut(duration: 1.2).repeatForever(autoreverses: true) : .default,
+ value: isPulsing
+ )
+ .onAppear { if isWorking { isPulsing = true } }
+ .onChange(of: status) { _, _ in isPulsing = (status == .working) }
+ }
+}
+
+private struct MinimalDotView: View {
+ let status: SessionStatus
+ @State private var isPulsing = false
+
+ private var needsPulse: Bool { status == .needsInput || status == .error }
+
+ var body: some View {
+ ZStack {
+ if needsPulse {
+ Circle()
+ .fill(Color.orange.opacity(0.3))
+ .frame(width: 20, height: 20)
+ .scaleEffect(isPulsing ? 1.4 : 0.8)
+ .opacity(isPulsing ? 0 : 0.6)
+ }
+ Circle()
+ .fill(dotColor)
+ .frame(width: 10, height: 10)
+ .scaleEffect(isPulsing && needsPulse ? 1.15 : 1.0)
+ }
+ .frame(width: 18, height: 18)
+ .animation(
+ needsPulse ? .easeInOut(duration: 1.5).repeatForever(autoreverses: true) : .default,
+ value: isPulsing
+ )
+ .onAppear { if needsPulse { isPulsing = true } }
+ .onChange(of: status) { _, _ in withAnimation { isPulsing = needsPulse } }
+ }
+
+ private var dotColor: Color {
+ switch status {
+ case .needsInput, .error: return .orange
+ case .compacting: return .purple
+ case .idle: return .secondary.opacity(0.4)
+ case .completed: return .secondary.opacity(0.3)
+ default: return .secondary.opacity(0.4)
+ }
+ }
+}
+
+struct ClaudeSparkleView: View {
+ private static let phases: [String] = ["·", "✢", "✳", "✶", "✻", "✽"]
+ private static let cycle: [String] = phases + phases.dropFirst().dropLast().reversed()
+ @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: 14))
+ .foregroundStyle(.secondary.opacity(opacity))
+ .onReceive(timer) { _ in
+ currentIndex = (currentIndex + 1) % Self.cycle.count
+ }
+ }
+
+ private var opacity: Double {
+ let pos = Double(currentIndex) / Double(Self.cycle.count - 1)
+ return 0.4 + sin(pos * .pi) * 0.6
+ }
+}
diff --git a/CodePulse-iOS/Views/IOSTheme.swift b/CodePulse-iOS/Views/IOSTheme.swift
new file mode 100644
index 00000000..75a47e08
--- /dev/null
+++ b/CodePulse-iOS/Views/IOSTheme.swift
@@ -0,0 +1,34 @@
+import SwiftUI
+
+struct CodePulseTheme: Sendable {
+ let isDark: Bool
+
+ var background: Color {
+ isDark ? Color(red: 0.11, green: 0.11, blue: 0.12) : .white
+ }
+ var cardBackground: Color {
+ isDark ? Color.white.opacity(0.05) : Color.black.opacity(0.03)
+ }
+ var primaryText: Color {
+ isDark ? Color(red: 0.96, green: 0.96, blue: 0.97) : Color(red: 0.11, green: 0.11, blue: 0.12)
+ }
+ var secondaryText: Color {
+ isDark ? Color(red: 0.56, green: 0.56, blue: 0.58) : Color(red: 0.53, green: 0.53, blue: 0.55)
+ }
+ var separator: Color {
+ isDark ? Color.white.opacity(0.1) : Color.black.opacity(0.08)
+ }
+ var accent: Color { .blue }
+ var warning: Color { .orange }
+}
+
+private struct ThemeKey: EnvironmentKey {
+ static let defaultValue = CodePulseTheme(isDark: false)
+}
+
+extension EnvironmentValues {
+ var theme: CodePulseTheme {
+ get { self[ThemeKey.self] }
+ set { self[ThemeKey.self] = newValue }
+ }
+}
diff --git a/CodePulse-macOS/App/CodePulseApp.swift b/CodePulse-macOS/App/CodePulseApp.swift
index fa9552a7..566a9069 100644
--- a/CodePulse-macOS/App/CodePulseApp.swift
+++ b/CodePulse-macOS/App/CodePulseApp.swift
@@ -30,15 +30,34 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
cloudKitSync = CloudKitSync(stateManager: stateManager)
menuBarController = MenuBarController(stateManager: stateManager)
- // Notification-only hook for instant permission detection
+ // Hook events: Notification, PermissionRequest, PreCompact, SessionStart, SessionEnd
hookServer.ensureHooksConfigured()
hookServer.onPermissionEvent = { [weak self] in
- self?.scanner.scan() // Trigger immediate rescan → state manager picks up permission
+ self?.scanner.scan()
+ }
+ hookServer.onSessionEvent = { [weak self] in
+ self?.scanner.scan()
+ }
+ hookServer.onHookSignal = { [weak self] sessionId, signalType, toolName in
+ self?.stateManager.transcriptWatcher.handleHookSignal(
+ sessionId: sessionId, signalType: signalType, toolName: toolName
+ )
+ self?.scanner.scan()
}
hookServer.start()
scanner.start()
- logger.info("CodePulse launched — JSONL transcript watcher + notification hook active")
+ logger.info("CodePulse launched — JSONL watcher + Notification/SessionStart/SessionEnd hooks active")
+
+ // Clean up orphan CloudKit records from prior crashes or stale sessions
+ Task {
+ do {
+ let activeIds = Set(scanner.activeSessions.keys)
+ try await CloudKitManager.shared.deleteOrphans(activeSessionIds: activeIds)
+ } catch {
+ logger.warning("Orphan cleanup failed: \(error.localizedDescription)")
+ }
+ }
}
func applicationWillTerminate(_ notification: Notification) {
diff --git a/CodePulse-macOS/Services/ClaudeHookServer.swift b/CodePulse-macOS/Services/ClaudeHookServer.swift
index 52919cdf..11809f46 100644
--- a/CodePulse-macOS/Services/ClaudeHookServer.swift
+++ b/CodePulse-macOS/Services/ClaudeHookServer.swift
@@ -36,6 +36,9 @@ final class ClaudeHookServer: @unchecked Sendable {
}
var onPermissionEvent: (@Sendable () -> 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
@@ -60,10 +63,12 @@ final class ClaudeHookServer: @unchecked Sendable {
let script = """
#!/bin/bash
# CodePulse: non-blocking hook notification
- # If CodePulse isn't running, curl fails silently — Claude Code is unaffected
+ # Backgrounds curl so synchronous hooks (SessionStart) return instantly.
+ # If CodePulse isn't running, curl fails silently — Claude Code is unaffected.
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 || true
+ -d "$HOOK_INPUT" 2>/dev/null &
+ exit 0
"""
try? script.write(to: scriptPath, atomically: true, encoding: .utf8)
@@ -109,17 +114,21 @@ final class ClaudeHookServer: @unchecked Sendable {
}
}
- // 2. Register single Notification command hook
+ // 2. Register command hooks for Notification, SessionStart, SessionEnd
let commandHook: [String: Any] = ["type": "command", "command": scriptPath]
- var notifEntries = hooks["Notification"] as? [[String: Any]] ?? []
- let alreadyPresent = notifEntries.contains { entry in
- guard let entryHooks = entry["hooks"] as? [[String: Any]] else { return false }
- return entryHooks.contains { ($0["command"] as? String) == scriptPath }
- }
- if !alreadyPresent {
- notifEntries.append(["hooks": [commandHook]])
- hooks["Notification"] = notifEntries
- changed = true
+ let hookEntry: [String: Any] = ["hooks": [commandHook]]
+
+ for event in ["Notification", "SessionStart", "SessionEnd", "PermissionRequest", "PreCompact"] {
+ var entries = hooks[event] as? [[String: Any]] ?? []
+ let alreadyPresent = entries.contains { entry in
+ guard let entryHooks = entry["hooks"] as? [[String: Any]] else { return false }
+ return entryHooks.contains { ($0["command"] as? String) == scriptPath }
+ }
+ if !alreadyPresent {
+ entries.append(hookEntry)
+ hooks[event] = entries
+ changed = true
+ }
}
if changed {
@@ -209,20 +218,66 @@ final class ClaudeHookServer: @unchecked Sendable {
let json = try? JSONSerialization.jsonObject(with: bodyData) as? [String: Any] else { return }
let eventName = json["hook_event_name"] as? String ?? ""
- guard eventName == "Notification" else { return } // Only care about Notification
-
let sessionId = json["session_id"] as? String
- guard let sessionId else { return }
-
- let notificationType = json["notification_type"] as? String
- ?? (json["message"] as? [String: Any])?["notification_type"] as? String
+ let toolName = json["tool_name"] as? String
+
+ switch eventName {
+ case "Notification":
+ guard let sessionId else { return }
+ 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 notificationType == "permission_prompt" {
+ case "PermissionRequest":
+ guard let sessionId else { return }
lock.lock()
_permissionSessions.insert(sessionId)
lock.unlock()
- logger.debug("Permission needed for session \(sessionId.prefix(8))...")
- DispatchQueue.main.async { [weak self] in self?.onPermissionEvent?() }
+ logger.debug("PermissionRequest for session \(sessionId.prefix(8))...")
+ DispatchQueue.main.async { [weak self] in
+ self?.onHookSignal?(sessionId, "permission_request", toolName)
+ self?.onPermissionEvent?()
+ }
+
+ case "PreCompact":
+ 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)
+ }
+
+ case "SessionStart":
+ logger.info("SessionStart hook fired\(sessionId.map { " for \($0.prefix(8))..." } ?? "")")
+ DispatchQueue.main.async { [weak self] in self?.onSessionEvent?() }
+
+ case "SessionEnd":
+ logger.info("SessionEnd hook fired\(sessionId.map { " for \($0.prefix(8))..." } ?? "")")
+ DispatchQueue.main.async { [weak self] in self?.onSessionEvent?() }
+
+ default:
+ break
}
}
}
diff --git a/CodePulse-macOS/Services/CloudKitSync.swift b/CodePulse-macOS/Services/CloudKitSync.swift
index f91fbf46..003dcb34 100644
--- a/CodePulse-macOS/Services/CloudKitSync.swift
+++ b/CodePulse-macOS/Services/CloudKitSync.swift
@@ -11,6 +11,7 @@ final class CloudKitSync {
private let stateManager: SessionStateManager
private var cancellables = Set<AnyCancellable>()
private var previousStates: [String: SessionState] = [:]
+ private var previousSessionIds: Set<String> = []
private var isSyncing = false
private var quotaBackoffUntil: Date?
@@ -34,30 +35,53 @@ final class CloudKitSync {
private func syncToCloud(_ sessions: [SessionState]) {
guard !isSyncing else { return }
- // Respect quota backoff — do NOT send any requests during backoff
+ // Respect quota backoff
if let backoff = quotaBackoffUntil, Date() < backoff { return }
quotaBackoffUntil = nil
- let changed = sessions.filter { session in
+ let currentIds = Set(sessions.map(\.sessionId))
+
+ // Sessions that disappeared or completed since last sync → delete from CloudKit
+ let completedIds = sessions.filter { $0.status == .completed }.map(\.sessionId)
+ let disappearedIds = previousSessionIds.subtracting(currentIds)
+ let toDelete = Array(Set(completedIds).union(disappearedIds))
+
+ // Active sessions with changed content → save to CloudKit
+ let toSave = sessions.filter { session in
session.status != .completed
&& previousStates[session.sessionId]?.updatedAt != session.updatedAt
}
- guard !changed.isEmpty else { return }
+
+ guard !toDelete.isEmpty || !toSave.isEmpty else {
+ previousSessionIds = currentIds
+ return
+ }
isSyncing = true
Task {
- defer { isSyncing = false }
+ defer {
+ isSyncing = false
+ previousSessionIds = currentIds
+ }
do {
- Self.log("saveBatch \(changed.count) sessions")
- try await CloudKitManager.shared.saveBatch(changed)
- Self.log("SUCCESS: saved \(changed.count)")
- // Verify fetch works
- let fetched = try await CloudKitManager.shared.fetchAll()
- Self.log("VERIFY: fetchAll returned \(fetched.count) records")
- for session in changed {
- previousStates[session.sessionId] = session
+ if !toDelete.isEmpty {
+ Self.log("deleteByIds \(toDelete.count) sessions")
+ try await CloudKitManager.shared.deleteByIds(toDelete)
+ Self.log("SUCCESS: deleted \(toDelete.count)")
+ for id in toDelete {
+ previousStates.removeValue(forKey: id)
+ }
+ }
+
+ if !toSave.isEmpty {
+ Self.log("saveBatch \(toSave.count) sessions")
+ try await CloudKitManager.shared.saveBatch(toSave)
+ Self.log("SUCCESS: saved \(toSave.count)")
+ for session in toSave {
+ previousStates[session.sessionId] = session
+ }
}
} catch let error as CKError where error.code == .quotaExceeded || error.code == .requestRateLimited {
let retryAfter = error.retryAfterSeconds ?? 600
diff --git a/CodePulse-macOS/Services/SessionStateManager.swift b/CodePulse-macOS/Services/SessionStateManager.swift
index da947583..c6ee4947 100644
--- a/CodePulse-macOS/Services/SessionStateManager.swift
+++ b/CodePulse-macOS/Services/SessionStateManager.swift
@@ -128,6 +128,8 @@ final class SessionStateManager: ObservableObject {
return .working
case .waitingForUser:
return .needsInput
+ case .compacting:
+ return .compacting
case .idle:
return .idle
}
diff --git a/CodePulse-macOS/Services/TranscriptWatcher.swift b/CodePulse-macOS/Services/TranscriptWatcher.swift
index 1c8e5061..18d0d09c 100644
--- a/CodePulse-macOS/Services/TranscriptWatcher.swift
+++ b/CodePulse-macOS/Services/TranscriptWatcher.swift
@@ -3,7 +3,8 @@ import os
private let logger = Logger(subsystem: "com.pokai.CodePulse", category: "TranscriptWatcher")
-/// Per-session transcript state derived from incremental JSONL parsing
+/// Per-session transcript state derived from incremental JSONL parsing.
+/// State machine inspired by claude-status (gmr/claude-status-plugin).
struct TranscriptState: Sendable {
var status: TranscriptStatus = .idle
var lastEvent: String = ""
@@ -35,70 +36,99 @@ struct TranscriptState: Sendable {
enum TranscriptStatus: Sendable {
case working
case waitingForUser
+ case compacting
case idle
}
/// Incrementally parses JSONL transcript files to detect session state.
-/// Replaces hook-based detection — zero impact on Claude Code.
+/// Zero impact on Claude Code — reads files only, no hooks for tool events.
@MainActor
final class TranscriptWatcher {
- /// Per-session tracking
+ /// Per-session tracking (mirrors claude-status's DaemonState)
private struct SessionTracker {
var fileOffset: UInt64 = 0
var lineBuffer: String = ""
var state: TranscriptState = TranscriptState()
+
+ // Agent tracking: tool_use IDs for Agent tools (subagents)
+ var activeAgents: Set<String> = []
+ // All active tool_use IDs (for permission timeout heuristic)
var activeToolIds: Set<String> = []
- var hadToolsInTurn: Bool = false
var lastToolStartTime: Date?
+
+ // Compaction state: when true, suppress replayed user/progress messages
+ var isCompacting: Bool = false
}
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.
+ /// Permission timeout — tool started but no result
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
}
+ /// 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 }
+ tracker.state.lastActivityTime = Date()
+
+ switch signalType {
+ case "permission_request":
+ tracker.state.status = .waitingForUser
+ tracker.state.lastEvent = toolName.map { "Permission: \($0)" } ?? "Needs permission"
+ case "elicitation_dialog":
+ 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 "pre_compact":
+ tracker.state.status = .compacting
+ tracker.state.lastEvent = "Compacting context..."
+ tracker.isCompacting = true
+ default:
+ break
+ }
+
+ trackers[sessionId] = tracker
+ }
+
/// 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)
+ // First time — skip to end but detect initial status from tail
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
+ let (initialStatus, lastEvent) = detectInitialStatus(url: jsonlURL)
+ tracker.state.status = initialStatus
+ if let lastEvent { tracker.state.lastEvent = lastEvent }
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 {
@@ -109,10 +139,9 @@ final class TranscriptWatcher {
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
+ tracker.lineBuffer = lines.removeLast()
for line in lines where !line.isEmpty {
processLine(line, tracker: &tracker)
@@ -121,7 +150,6 @@ final class TranscriptWatcher {
trackers[sessionId] = tracker
}
- /// Remove tracking for a session (when it completes)
func removeSession(_ sessionId: String) {
trackers.removeValue(forKey: sessionId)
}
@@ -132,6 +160,19 @@ final class TranscriptWatcher {
guard let data = line.data(using: .utf8),
let entry = try? decoder.decode(JSONLTranscriptEntry.self, from: data) else { return }
+ // Skip meta messages (plugin commands, local output)
+ if entry.isMeta == true { return }
+
+ // Compaction detection via agentId prefix
+ if let agentId = entry.agentId, agentId.hasPrefix("acompact-") {
+ if tracker.state.status != .compacting {
+ tracker.state.status = .compacting
+ tracker.state.lastEvent = "Compacting context..."
+ tracker.isCompacting = true
+ }
+ return
+ }
+
switch entry.type {
case "assistant":
processAssistant(entry, tracker: &tracker)
@@ -139,6 +180,8 @@ final class TranscriptWatcher {
processUser(entry, tracker: &tracker)
case "system":
processSystem(entry, tracker: &tracker)
+ case "progress":
+ processProgress(entry, tracker: &tracker)
default:
break
}
@@ -147,6 +190,11 @@ final class TranscriptWatcher {
private func processAssistant(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
guard let message = entry.message else { return }
+ // An assistant response clears compaction flag
+ if tracker.isCompacting {
+ tracker.isCompacting = false
+ }
+
// Update model and usage
if let model = message.model, !model.isEmpty {
tracker.state.model = model
@@ -160,65 +208,153 @@ final class TranscriptWatcher {
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" }
+ // Track tool_use blocks
+ let toolUseBlocks = content.filter { $0.type == "tool_use" }
+ for block in toolUseBlocks {
+ if let id = block.id {
+ tracker.activeToolIds.insert(id)
+ // Track Agent tool specifically for subagent awareness
+ if block.name == "Agent" {
+ tracker.activeAgents.insert(id)
+ }
+ }
+ if let name = block.name {
+ tracker.state.toolName = name
+ tracker.state.lastEvent = formatToolStatus(name: name, input: block.input)
+ }
+ }
if !toolUseBlocks.isEmpty {
+ tracker.lastToolStartTime = Date()
+ }
+
+ // Determine state from stop_reason (key insight from claude-status)
+ switch message.stopReason {
+ case nil:
+ // Still streaming — active
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)
- }
+ case "tool_use":
+ // About to execute tools — active
+ tracker.state.status = .working
+
+ case "end_turn":
+ if !tracker.activeAgents.isEmpty {
+ // Subagents still running — stay active
+ tracker.state.status = .working
+ tracker.state.lastEvent = "Running sub-agent"
+ } else {
+ // Turn finished — idle
+ tracker.state.status = .idle
+ tracker.state.lastEvent = ""
+ tracker.activeToolIds.removeAll()
+ tracker.lastToolStartTime = nil
}
- tracker.lastToolStartTime = Date()
- } else if content.contains(where: { $0.type == "text" }) {
- // Text-only response — agent is working (generating text)
+
+ case "stop_sequence", "max_tokens":
+ tracker.state.status = .idle
+ tracker.state.lastEvent = ""
+ tracker.activeToolIds.removeAll()
+ tracker.activeAgents.removeAll()
+ tracker.lastToolStartTime = nil
+
+ default:
+ // Unknown stop_reason — treat as still working if we have tool activity
+ if !toolUseBlocks.isEmpty || !tracker.activeToolIds.isEmpty {
+ tracker.state.status = .working
+ }
+ }
+
+ // If no stop_reason and has text, still working
+ if message.stopReason == nil, content.contains(where: { $0.type == "text" }), toolUseBlocks.isEmpty {
tracker.state.status = .working
- tracker.state.lastEvent = "Thinking..."
+ if tracker.state.lastEvent.isEmpty {
+ tracker.state.lastEvent = "Thinking..."
+ }
}
}
private func processUser(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
+ // During compaction, user messages are replayed context — skip
+ if tracker.isCompacting { return }
+
guard let content = entry.message?.content else { return }
let toolResults = content.filter { $0.type == "tool_result" }
if !toolResults.isEmpty {
- // Tool completed
+ // Tool completed — remove from tracking
for result in toolResults {
if let id = result.toolUseId {
tracker.activeToolIds.remove(id)
+ // Only remove from activeAgents if not async
+ if result.isAsync != true {
+ tracker.activeAgents.remove(id)
+ }
}
}
if tracker.activeToolIds.isEmpty {
- tracker.hadToolsInTurn = false
tracker.lastToolStartTime = nil
}
- } else {
- // New user prompt — new turn starting
+ } else if entry.promptId != nil {
+ // Real user prompt (has promptId) — new turn starting
tracker.state.status = .working
tracker.state.lastEvent = "Processing prompt..."
tracker.activeToolIds.removeAll()
- tracker.hadToolsInTurn = false
+ tracker.activeAgents.removeAll()
tracker.lastToolStartTime = nil
+ } else {
+ // User message without promptId and without tool_result — likely still working
+ tracker.state.status = .working
+ tracker.state.lastEvent = "Processing..."
}
}
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"
+ switch entry.subtype {
+ case "turn_duration", "stop_hook_summary":
+ // Turn end signals — stop_hook_summary fires after hooks complete,
+ // turn_duration may follow (but not always). Either one marks turn as done.
+ tracker.activeAgents.removeAll()
tracker.activeToolIds.removeAll()
- tracker.hadToolsInTurn = false
tracker.lastToolStartTime = nil
+ if tracker.state.status == .working || tracker.state.status == .compacting {
+ tracker.state.status = .idle
+ tracker.state.lastEvent = ""
+ }
+
+ case "compact_boundary":
+ tracker.state.status = .compacting
+ tracker.state.lastEvent = "Compacting context..."
+ tracker.isCompacting = true
+
+ default:
+ break
+ }
+ }
+
+ private func processProgress(_ entry: JSONLTranscriptEntry, tracker: inout SessionTracker) {
+ // During compaction, progress messages are replayed — skip
+ if tracker.isCompacting { return }
+
+ guard let dataType = entry.data?.type else { return }
+
+ switch dataType {
+ case "agent_progress":
+ tracker.state.status = .working
+ tracker.state.lastEvent = "Running sub-agent"
+ case "bash_progress":
+ tracker.state.status = .working
+ tracker.state.lastEvent = "Running command..."
+ case "mcp_progress":
+ tracker.state.status = .working
+ tracker.state.lastEvent = "MCP tool running..."
+ case "hook_progress":
+ // Hooks running (e.g. notify.sh) — NOT real work, don't change state
+ break
+ default:
+ break
}
}
@@ -230,6 +366,7 @@ final class TranscriptWatcher {
// Permission heuristic: tool started but no result after timeout
if !tracker.activeToolIds.isEmpty,
+ tracker.activeAgents.isEmpty, // Don't timeout on subagents
let toolStart = tracker.lastToolStartTime,
now.timeIntervalSince(toolStart) > permissionTimeoutSeconds {
if tracker.state.status == .working {
@@ -238,19 +375,62 @@ final class TranscriptWatcher {
}
}
- // Working but no new data → turn_duration was missed or hasn't arrived yet
+ // Working with no tools and no new data → likely idle
if tracker.state.status == .working,
tracker.activeToolIds.isEmpty,
- sinceLastActivity > idleTimeoutSeconds {
- tracker.state.status = .waitingForUser
- tracker.state.lastEvent = "Waiting for input"
+ tracker.activeAgents.isEmpty,
+ sinceLastActivity > 15.0 {
+ tracker.state.status = .idle
+ tracker.state.lastEvent = ""
}
+ }
- // Waiting but no new data for even longer → truly idle
- if tracker.state.status == .waitingForUser,
- sinceLastActivity > idleTimeoutSeconds * 3 {
- tracker.state.status = .idle
+ // MARK: - Initial Status Detection
+
+ private func detectInitialStatus(url: URL) -> (TranscriptStatus, String?) {
+ let lines = JSONLTailReader.readTail(url: url, lineCount: 20)
+
+ for line in lines.reversed() {
+ guard let data = line.data(using: .utf8),
+ let entry = try? decoder.decode(JSONLTranscriptEntry.self, from: data) else { continue }
+
+ if entry.isMeta == true { continue }
+
+ if entry.type == "system" {
+ if entry.subtype == "turn_duration" || entry.subtype == "stop_hook_summary" {
+ return (.idle, nil)
+ }
+ if entry.subtype == "compact_boundary" { return (.compacting, "Compacting context...") }
+ }
+
+ if entry.type == "assistant" {
+ if let stopReason = entry.message?.stopReason {
+ if stopReason == "end_turn" || stopReason == "stop_sequence" || stopReason == "max_tokens" {
+ return (.idle, nil)
+ }
+ }
+ if let content = entry.message?.content,
+ let toolBlock = content.first(where: { $0.type == "tool_use" }),
+ let toolName = toolBlock.name {
+ return (.working, formatToolStatus(name: toolName, input: toolBlock.input))
+ }
+ return (.working, "Thinking...")
+ }
+
+ if entry.type == "user" {
+ if let content = entry.message?.content,
+ content.contains(where: { $0.type == "tool_result" }) {
+ return (.working, nil)
+ }
+ return (.working, "Processing prompt...")
+ }
+
+ if entry.type == "progress" {
+ return (.working, "Running...")
+ }
}
+
+ return (.idle, nil)
}
// MARK: - Display Formatting
diff --git a/CodePulse-macOS/Utilities/JSONLTailReader.swift b/CodePulse-macOS/Utilities/JSONLTailReader.swift
index 7ea81ec0..99723d22 100644
--- a/CodePulse-macOS/Utilities/JSONLTailReader.swift
+++ b/CodePulse-macOS/Utilities/JSONLTailReader.swift
@@ -32,12 +32,15 @@ struct JSONLContentBlock: Codable {
let type: String
let id: String?
let name: String?
+ let text: String?
let input: JSONLToolInput?
let toolUseId: String?
+ let isAsync: Bool?
enum CodingKeys: String, CodingKey {
- case type, id, name, input
+ case type, id, name, text, input
case toolUseId = "tool_use_id"
+ case isAsync
}
}
@@ -66,11 +69,19 @@ struct JSONLTranscriptMessage: Codable {
}
}
+struct JSONLProgressData: Codable {
+ let type: String?
+}
+
struct JSONLTranscriptEntry: Codable {
let type: String?
let subtype: String?
let message: JSONLTranscriptMessage?
let timestamp: String?
+ let isMeta: Bool?
+ let agentId: String?
+ let promptId: String?
+ let data: JSONLProgressData?
}
struct JSONLSessionInfo {
diff --git a/CodePulse.xcodeproj/project.pbxproj b/CodePulse.xcodeproj/project.pbxproj
index 3059df2a..7e675b6a 100644
--- a/CodePulse.xcodeproj/project.pbxproj
+++ b/CodePulse.xcodeproj/project.pbxproj
@@ -39,6 +39,9 @@
EF0A0CEAD3C7B875064F8556 /* LiveActivityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADC1A963B2C1124F480F9CE /* LiveActivityManager.swift */; };
F1E2D3C4B5A6F7E8D9C0B1A2 /* SessionTagView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1F2 /* SessionTagView.swift */; };
F4F54F91459EE6A15DD7B246 /* CodePulseIOSApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8453D8BE6EE838E1B9EA4588 /* CodePulseIOSApp.swift */; };
+ B1C2D3E4F5A6B7C8D9E0F1A1 /* IOSTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1A1 /* IOSTheme.swift */; };
+ B1C2D3E4F5A6B7C8D9E0F1A2 /* IOSStatusIndicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1A2 /* IOSStatusIndicator.swift */; };
+ B1C2D3E4F5A6B7C8D9E0F1A3 /* IOSSessionTagView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1A3 /* IOSSessionTagView.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -100,6 +103,9 @@
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>"; };
+ A1B2C3D4E5F6A7B8C9D0E1A1 /* IOSTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSTheme.swift; sourceTree = "<group>"; };
+ A1B2C3D4E5F6A7B8C9D0E1A2 /* IOSStatusIndicator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSStatusIndicator.swift; sourceTree = "<group>"; };
+ A1B2C3D4E5F6A7B8C9D0E1A3 /* IOSSessionTagView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IOSSessionTagView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -167,6 +173,9 @@
DF291DF4A4EF932B774F227D /* IOSRootView.swift */,
9C01C9748A39F3475869F956 /* IOSSessionDetailView.swift */,
A01A225437E7A00B3337883E /* IOSSessionListView.swift */,
+ A1B2C3D4E5F6A7B8C9D0E1A1 /* IOSTheme.swift */,
+ A1B2C3D4E5F6A7B8C9D0E1A2 /* IOSStatusIndicator.swift */,
+ A1B2C3D4E5F6A7B8C9D0E1A3 /* IOSSessionTagView.swift */,
);
path = Views;
sourceTree = "<group>";
@@ -426,6 +435,9 @@
0B6B1D4B20837A47EAF88322 /* IOSSessionDetailView.swift in Sources */,
A30C11E610763F5064698D43 /* IOSSessionListView.swift in Sources */,
EF0A0CEAD3C7B875064F8556 /* LiveActivityManager.swift in Sources */,
+ B1C2D3E4F5A6B7C8D9E0F1A1 /* IOSTheme.swift in Sources */,
+ B1C2D3E4F5A6B7C8D9E0F1A2 /* IOSStatusIndicator.swift in Sources */,
+ B1C2D3E4F5A6B7C8D9E0F1A3 /* IOSSessionTagView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -587,6 +599,7 @@
CODE_SIGN_IDENTITY = "iPhone Developer";
DEVELOPMENT_TEAM = DEVELOPMENT_TEAM_REDACTED;
GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_NSSupportsLiveActivities = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
@@ -613,6 +626,7 @@
CODE_SIGN_IDENTITY = "iPhone Developer";
DEVELOPMENT_TEAM = DEVELOPMENT_TEAM_REDACTED;
GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_NSSupportsLiveActivities = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
diff --git a/CodePulse.xcodeproj/xcshareddata/xcschemes/CodePulse-iOS.xcscheme b/CodePulse.xcodeproj/xcshareddata/xcschemes/CodePulse-iOS.xcscheme
new file mode 100644
index 00000000..ba1b596b
--- /dev/null
+++ b/CodePulse.xcodeproj/xcshareddata/xcschemes/CodePulse-iOS.xcscheme
@@ -0,0 +1,78 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "2620"
+ version = "1.7">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES"
+ buildArchitectures = "Automatic">
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "842C52E994476FBBD71C5E66"
+ BuildableName = "CodePulse.app"
+ BlueprintName = "CodePulse-iOS"
+ ReferencedContainer = "container:CodePulse.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ shouldAutocreateTestPlan = "YES">
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ launchStyle = "0"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "842C52E994476FBBD71C5E66"
+ BuildableName = "CodePulse.app"
+ BlueprintName = "CodePulse-iOS"
+ ReferencedContainer = "container:CodePulse.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Release"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "842C52E994476FBBD71C5E66"
+ BuildableName = "CodePulse.app"
+ BlueprintName = "CodePulse-iOS"
+ ReferencedContainer = "container:CodePulse.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/CodePulse.xcodeproj/xcshareddata/xcschemes/CodePulseLiveActivity.xcscheme b/CodePulse.xcodeproj/xcshareddata/xcschemes/CodePulseLiveActivity.xcscheme
new file mode 100644
index 00000000..cdbf7720
--- /dev/null
+++ b/CodePulse.xcodeproj/xcshareddata/xcschemes/CodePulseLiveActivity.xcscheme
@@ -0,0 +1,97 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "2620"
+ wasCreatedForAppExtension = "YES"
+ version = "2.0">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES"
+ buildArchitectures = "Automatic">
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "6B3B927655EA5C595A71E513"
+ BuildableName = "CodePulseLiveActivity.appex"
+ BlueprintName = "CodePulseLiveActivity"
+ ReferencedContainer = "container:CodePulse.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "842C52E994476FBBD71C5E66"
+ BuildableName = "CodePulse.app"
+ BlueprintName = "CodePulse-iOS"
+ ReferencedContainer = "container:CodePulse.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ shouldAutocreateTestPlan = "YES">
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = ""
+ selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
+ launchStyle = "0"
+ askForAppToLaunch = "Yes"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES"
+ launchAutomaticallySubstyle = "2">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "842C52E994476FBBD71C5E66"
+ BuildableName = "CodePulse.app"
+ BlueprintName = "CodePulse-iOS"
+ ReferencedContainer = "container:CodePulse.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Release"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES"
+ askForAppToLaunch = "Yes"
+ launchAutomaticallySubstyle = "2">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "842C52E994476FBBD71C5E66"
+ BuildableName = "CodePulse.app"
+ BlueprintName = "CodePulse-iOS"
+ ReferencedContainer = "container:CodePulse.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/CodePulseLiveActivity/CodePulseLiveActivityWidget.swift b/CodePulseLiveActivity/CodePulseLiveActivityWidget.swift
index 26ff3997..01083269 100644
--- a/CodePulseLiveActivity/CodePulseLiveActivityWidget.swift
+++ b/CodePulseLiveActivity/CodePulseLiveActivityWidget.swift
@@ -38,7 +38,7 @@ struct CodePulseLiveActivityWidget: Widget {
if let task = context.state.currentTask {
Text("\u{25FC} \(task)")
.font(.caption)
- .foregroundStyle(.cyan)
+ .foregroundStyle(.blue)
.lineLimit(1)
}
Spacer()
@@ -78,7 +78,7 @@ struct CodePulseLiveActivityWidget: Widget {
if let task = context.state.currentTask {
Text("\u{25FC} \(task)")
.font(.caption2)
- .foregroundStyle(.cyan)
+ .foregroundStyle(.blue)
.lineLimit(1)
}
Spacer()
@@ -115,10 +115,11 @@ struct CodePulseLiveActivityWidget: Widget {
private func statusColor(_ status: String) -> Color {
switch status {
- case "working": return .green
- case "idle": return .cyan
+ case "working": return .blue
+ case "idle": return .secondary
case "needsInput": return .orange
- case "error": return .red
+ case "compacting": return .purple
+ case "error": return .orange
default: return .gray
}
}
@@ -128,6 +129,7 @@ struct CodePulseLiveActivityWidget: Widget {
case "working": return "Working"
case "idle": return "Idle"
case "needsInput": return "Needs Input"
+ case "compacting": return "Compacting"
case "error": return "Error"
default: return "Done"
}
@@ -135,9 +137,9 @@ struct CodePulseLiveActivityWidget: Widget {
private func taskColor(_ status: TaskStatus) -> Color {
switch status {
- case .completed: return .green
- case .inProgress: return .cyan
- case .pending: return Color(.systemGray3)
+ case .completed: return .blue
+ case .inProgress: return .blue.opacity(0.4)
+ case .pending: return Color(.systemGray4)
}
}
}
diff --git a/CodePulseShared/Sources/CloudKit/CloudKitManager.swift b/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
index eaaa74c1..5e448a45 100644
--- a/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
+++ b/CodePulseShared/Sources/CloudKit/CloudKitManager.swift
@@ -73,21 +73,33 @@ public final class CloudKitManager: Sendable {
logger.info("Subscribed to CloudKit changes")
}
- // MARK: - Cleanup
+ // MARK: - Delete
- public func deleteCompleted(olderThan hours: Int = 24) async throws {
- let cutoff = Date().addingTimeInterval(TimeInterval(-hours * 3600))
- let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
- NSPredicate(format: "status == %@", "completed"),
- NSPredicate(format: "updatedAt < %@", cutoff as NSDate),
- ])
- let query = CKQuery(recordType: CKRecordMapper.recordType, predicate: predicate)
- let (results, _) = try await database.records(matching: query)
- for (id, _) in results {
+ /// Delete specific session records by ID (called when sessions complete on macOS)
+ public func deleteByIds(_ sessionIds: [String]) async throws {
+ guard !sessionIds.isEmpty else { return }
+ let recordIDs = sessionIds.map { CKRecord.ID(recordName: $0) }
+ for id in recordIDs {
try? await database.deleteRecord(withID: id)
}
- if !results.isEmpty {
- logger.info("Deleted \(results.count) completed sessions from CloudKit")
+ logger.info("Deleted \(sessionIds.count) session records from CloudKit")
+ }
+
+ /// Delete all CloudKit records whose sessionId is NOT in the active set.
+ /// Called once on macOS app launch to clean up stale records from prior crashes.
+ public func deleteOrphans(activeSessionIds: Set<String>) async throws {
+ let query = CKQuery(recordType: CKRecordMapper.recordType, predicate: NSPredicate(value: true))
+ let (results, _) = try await database.records(matching: query, resultsLimit: 50)
+ var deletedCount = 0
+ for (id, result) in results {
+ guard case .success = result else { continue }
+ if !activeSessionIds.contains(id.recordName) {
+ try? await database.deleteRecord(withID: id)
+ deletedCount += 1
+ }
+ }
+ if deletedCount > 0 {
+ logger.info("Cleaned up \(deletedCount) orphan records from CloudKit")
}
}
}
diff --git a/CodePulseShared/Sources/Models/SessionStatus.swift b/CodePulseShared/Sources/Models/SessionStatus.swift
index c6ac018c..af54869a 100644
--- a/CodePulseShared/Sources/Models/SessionStatus.swift
+++ b/CodePulseShared/Sources/Models/SessionStatus.swift
@@ -4,15 +4,17 @@ public enum SessionStatus: String, Codable, Sendable {
case working
case idle
case needsInput
+ case compacting
case error
case completed
public var color: Color {
switch self {
- case .working: return .green
- case .idle: return .cyan
+ case .working: return .blue
+ case .idle: return .secondary
case .needsInput: return .orange
- case .error: return .red
+ case .compacting: return .purple
+ case .error: return .orange
case .completed: return .gray
}
}
@@ -22,6 +24,7 @@ public enum SessionStatus: String, Codable, Sendable {
case .working: return "Working"
case .idle: return "Idle"
case .needsInput: return "Needs Input"
+ case .compacting: return "Compacting"
case .error: return "Error"
case .completed: return "Completed"
}
@@ -29,7 +32,7 @@ public enum SessionStatus: String, Codable, Sendable {
public var isActive: Bool {
switch self {
- case .working, .idle, .needsInput, .error: return true
+ case .working, .idle, .needsInput, .compacting, .error: return true
case .completed: return false
}
}
diff --git a/docs/superpowers/plans/2026-03-18-live-activity-and-session-cleanup.md b/docs/superpowers/plans/2026-03-18-live-activity-and-session-cleanup.md
new file mode 100644
index 00000000..c972b54d
--- /dev/null
+++ b/docs/superpowers/plans/2026-03-18-live-activity-and-session-cleanup.md
@@ -0,0 +1,274 @@
+# Live Activity Fix + CloudKit Session Cleanup
+
+> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Fix Live Activity / Dynamic Island not showing on iOS, and ensure dead sessions are deleted from CloudKit so iOS doesn't display ghost sessions.
+
+**Architecture:** Two independent fixes: (1) Add missing `NSSupportsLiveActivities` build setting to iOS target, (2) Change CloudKitSync to delete CloudKit records when sessions complete (PID death), plus a startup orphan cleanup.
+
+**Tech Stack:** Swift 6, CloudKit, ActivityKit, WidgetKit
+
+---
+
+## File Map
+
+| File | Action | Responsibility |
+|------|--------|----------------|
+| `CodePulse.xcodeproj/project.pbxproj` | Modify | Add `NSSupportsLiveActivities = YES` to iOS target build settings (Debug + Release) |
+| `CodePulse-macOS/Services/CloudKitSync.swift` | Modify | Sync completed sessions as deletes, not saves |
+| `CodePulseShared/Sources/CloudKit/CloudKitManager.swift` | Modify | Add `deleteByIds()` and `deleteOrphans()` methods |
+| `CodePulse-macOS/App/CodePulseApp.swift` | Modify | Call orphan cleanup on launch |
+
+---
+
+### Task 1: Enable Live Activity in iOS build settings
+
+**Files:**
+- Modify: `CodePulse.xcodeproj/project.pbxproj:601-606` (iOS Release build settings)
+- Modify: `CodePulse.xcodeproj/project.pbxproj:627-632` (iOS Debug build settings)
+
+The iOS target is missing `INFOPLIST_KEY_NSSupportsLiveActivities = YES`. Without this, `Activity.request()` fails and no Live Activity or Dynamic Island appears.
+
+- [ ] **Step 1: Add NSSupportsLiveActivities to iOS Debug build settings**
+
+In `project.pbxproj`, inside the iOS Debug `XCBuildConfiguration` (section starting at line 620, `9A811AEDB402F850CF77C133`), add after the `GENERATE_INFOPLIST_FILE = YES;` line:
+
+```
+INFOPLIST_KEY_NSSupportsLiveActivities = YES;
+```
+
+- [ ] **Step 2: Add NSSupportsLiveActivities to iOS Release build settings**
+
+In `project.pbxproj`, inside the iOS Release `XCBuildConfiguration` (section starting at line 594, `74301E9EAFCD478E76A7FDEF`), add after the `GENERATE_INFOPLIST_FILE = YES;` line:
+
+```
+INFOPLIST_KEY_NSSupportsLiveActivities = YES;
+```
+
+- [ ] **Step 3: Build iOS target to verify**
+
+Run: `xcodebuild -project CodePulse.xcodeproj -scheme CodePulse-iOS -destination 'generic/platform=iOS' -configuration Debug build 2>&1 | tail -5`
+Expected: BUILD SUCCEEDED
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add CodePulse.xcodeproj/project.pbxproj
+git commit -m "fix: add NSSupportsLiveActivities to iOS target for Dynamic Island"
+```
+
+---
+
+### Task 2: Add CloudKit delete methods
+
+**Files:**
+- Modify: `CodePulseShared/Sources/CloudKit/CloudKitManager.swift`
+
+Add two methods: `deleteByIds` for targeted deletion when sessions complete, and `deleteOrphans` for startup cleanup of stale records.
+
+- [ ] **Step 1: Add deleteByIds method**
+
+Add to `CloudKitManager` after `deleteCompleted`:
+
+```swift
+/// Delete specific session records by ID (called when sessions complete on macOS)
+public func deleteByIds(_ sessionIds: [String]) async throws {
+ guard !sessionIds.isEmpty else { return }
+ let recordIDs = sessionIds.map { CKRecord.ID(recordName: $0) }
+ for id in recordIDs {
+ try? await database.deleteRecord(withID: id)
+ }
+ logger.info("Deleted \(sessionIds.count) session records from CloudKit")
+}
+```
+
+- [ ] **Step 2: Add deleteOrphans method**
+
+Add to `CloudKitManager` after `deleteByIds`:
+
+```swift
+/// Delete all CloudKit records whose sessionId is NOT in the active set.
+/// Called once on macOS app launch to clean up stale records from prior crashes.
+public func deleteOrphans(activeSessionIds: Set<String>) async throws {
+ let query = CKQuery(recordType: CKRecordMapper.recordType, predicate: NSPredicate(value: true))
+ let (results, _) = try await database.records(matching: query, resultsLimit: 50)
+ var deletedCount = 0
+ for (id, result) in results {
+ guard case .success = result else { continue }
+ if !activeSessionIds.contains(id.recordName) {
+ try? await database.deleteRecord(withID: id)
+ deletedCount += 1
+ }
+ }
+ if deletedCount > 0 {
+ logger.info("Cleaned up \(deletedCount) orphan records from CloudKit")
+ }
+}
+```
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add CodePulseShared/Sources/CloudKit/CloudKitManager.swift
+git commit -m "feat: add deleteByIds and deleteOrphans to CloudKitManager"
+```
+
+---
+
+### Task 3: Sync session deletion to CloudKit
+
+**Files:**
+- Modify: `CodePulse-macOS/Services/CloudKitSync.swift`
+
+When `SessionStateManager` marks a session as `.completed` (PID died), CloudKitSync should delete it from CloudKit instead of ignoring it.
+
+- [ ] **Step 1: Track previous session IDs for disappearance detection**
+
+Add a property to `CloudKitSync`:
+
+```swift
+private var previousSessionIds: Set<String> = []
+```
+
+- [ ] **Step 2: Rewrite syncToCloud to handle deletions**
+
+Replace the `syncToCloud` method with logic that:
+1. Finds sessions that disappeared or became `.completed` since last sync → delete from CloudKit
+2. Syncs changed active (non-completed) sessions → save to CloudKit
+
+```swift
+private func syncToCloud(_ sessions: [SessionState]) {
+ guard !isSyncing else { return }
+
+ // Respect quota backoff
+ if let backoff = quotaBackoffUntil, Date() < backoff { return }
+ quotaBackoffUntil = nil
+
+ let currentIds = Set(sessions.map(\.sessionId))
+
+ // Sessions that disappeared or completed since last sync → delete from CloudKit
+ let completedIds = sessions.filter { $0.status == .completed }.map(\.sessionId)
+ let disappearedIds = previousSessionIds.subtracting(currentIds)
+ let toDelete = Array(Set(completedIds).union(disappearedIds))
+
+ // Active sessions with changed content → save to CloudKit
+ let toSave = sessions.filter { session in
+ session.status != .completed
+ && previousStates[session.sessionId]?.updatedAt != session.updatedAt
+ }
+
+ guard !toDelete.isEmpty || !toSave.isEmpty else {
+ previousSessionIds = currentIds
+ return
+ }
+
+ isSyncing = true
+
+ Task {
+ defer {
+ isSyncing = false
+ previousSessionIds = currentIds
+ }
+
+ do {
+ if !toDelete.isEmpty {
+ Self.log("deleteByIds \(toDelete.count) sessions")
+ try await CloudKitManager.shared.deleteByIds(toDelete)
+ Self.log("SUCCESS: deleted \(toDelete.count)")
+ for id in toDelete {
+ previousStates.removeValue(forKey: id)
+ }
+ }
+
+ if !toSave.isEmpty {
+ Self.log("saveBatch \(toSave.count) sessions")
+ try await CloudKitManager.shared.saveBatch(toSave)
+ Self.log("SUCCESS: saved \(toSave.count)")
+ for session in toSave {
+ previousStates[session.sessionId] = session
+ }
+ }
+ } catch let error as CKError where error.code == .quotaExceeded || error.code == .requestRateLimited {
+ let retryAfter = error.retryAfterSeconds ?? 600
+ Self.log("QUOTA: backoff \(Int(retryAfter * 2))s")
+ quotaBackoffUntil = Date().addingTimeInterval(retryAfter * 2)
+ } catch {
+ Self.log("ERROR: \(error)")
+ quotaBackoffUntil = Date().addingTimeInterval(300)
+ }
+ }
+}
+```
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add CodePulse-macOS/Services/CloudKitSync.swift
+git commit -m "fix: sync session deletions to CloudKit when PID dies"
+```
+
+---
+
+### Task 4: Orphan cleanup on macOS app launch
+
+**Files:**
+- Modify: `CodePulse-macOS/App/CodePulseApp.swift:25-50` (applicationDidFinishLaunching)
+
+On launch, after scanner starts, compare active sessions with CloudKit records and delete orphans. This cleans up any legacy ghost sessions.
+
+- [ ] **Step 1: Add orphan cleanup call after scanner.start()**
+
+Add after `scanner.start()` (line 49) in `applicationDidFinishLaunching`:
+
+```swift
+Task {
+ do {
+ let activeIds = Set(scanner.activeSessions.keys)
+ try await CloudKitManager.shared.deleteOrphans(activeSessionIds: activeIds)
+ } catch {
+ logger.warning("Orphan cleanup failed: \(error.localizedDescription)")
+ }
+}
+```
+
+- [ ] **Step 2: Add CloudKitManager import**
+
+Add at the top of `CodePulseApp.swift`:
+
+```swift
+import CloudKit
+```
+
+(CloudKitManager is in CodePulseShared which is already imported, but verify `CloudKitManager` is accessible.)
+
+- [ ] **Step 3: Build macOS target to verify**
+
+Run: `xcodebuild -project CodePulse.xcodeproj -scheme CodePulse-macOS -configuration Debug build 2>&1 | tail -5`
+Expected: BUILD SUCCEEDED
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add CodePulse-macOS/App/CodePulseApp.swift
+git commit -m "feat: clean up orphan CloudKit records on macOS app launch"
+```
+
+---
+
+### Task 5: Remove dead code
+
+**Files:**
+- Modify: `CodePulseShared/Sources/CloudKit/CloudKitManager.swift`
+
+`deleteCompleted(olderThan:)` is now unnecessary — session records are deleted immediately on completion, and orphans are cleaned on launch. Remove it to avoid confusion.
+
+- [ ] **Step 1: Remove deleteCompleted method**
+
+Delete the `deleteCompleted(olderThan:)` method (lines 78-92).
+
+- [ ] **Step 2: Commit**
+
+```bash
+git add CodePulseShared/Sources/CloudKit/CloudKitManager.swift
+git commit -m "chore: remove unused deleteCompleted method"
+```