cmux/Sources/Update/UpdateLogStore.swift
Lawrence Chen eb7c06ceb1 Fix high CPU usage from notifications and add regression tests
- Fix auto-updating Text(date, style: .time) causing continuous SwiftUI updates
  by using static formatting with .formatted(date:time:)
- Fix notification popover keeping SwiftUI observers active when closed by
  clearing contentViewController on popover close and recreating on open
- Fix focus loss when notifications arrive while typing by only setting
  focus in NotificationsPage when the page is visible
- Make Update Pill and Update Logs debug-only features
- Add CPU regression tests: test_cpu_usage.py, test_cpu_notifications.py
- Add lint test for auto-updating Text patterns: test_lint_swiftui_patterns.py
2026-01-29 17:02:16 -08:00

65 lines
2 KiB
Swift

import Foundation
import AppKit
final class UpdateLogStore {
static let shared = UpdateLogStore()
private let queue = DispatchQueue(label: "cmuxterm.update.log")
private var entries: [String] = []
private let maxEntries = 200
private let logURL: URL
private let formatter: ISO8601DateFormatter
private init() {
formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let logsDir = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first
?? FileManager.default.temporaryDirectory
logURL = logsDir.appendingPathComponent("Logs/cmuxterm-update.log")
ensureLogFile()
}
func append(_ message: String) {
#if DEBUG
let timestamp = formatter.string(from: Date())
let line = "[\(timestamp)] \(message)"
queue.async { [weak self] in
guard let self else { return }
entries.append(line)
if entries.count > maxEntries {
entries.removeFirst(entries.count - maxEntries)
}
appendToFile(line: line)
}
#endif
}
func snapshot() -> String {
queue.sync {
entries.joined(separator: "\n")
}
}
func logPath() -> String {
logURL.path
}
private func ensureLogFile() {
let directory = logURL.deletingLastPathComponent()
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
if !FileManager.default.fileExists(atPath: logURL.path) {
try? Data().write(to: logURL)
}
}
private func appendToFile(line: String) {
let data = Data((line + "\n").utf8)
if let handle = try? FileHandle(forWritingTo: logURL) {
try? handle.seekToEnd()
try? handle.write(contentsOf: data)
try? handle.close()
} else {
try? data.write(to: logURL, options: .atomic)
}
}
}